标签:c entity-framework entity-framework-4 entity-framework-4-1 code-first
这段代码小规模地表示我的问题:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> Friends { get; set; }
}
当我在实体框架(4.1)场景中使用此类时,系统会生成一个唯一的关系,认为Parent和Friends是同一关系的两个面.
如何在语义上区分属性,并在SQL Server中生成两个不同的关系(因为我们可以看到Friends与Parent :-)完全不同).
我尝试使用流畅的界面,但我想我不知道正确的调用.
谢谢大家.
Andrea Bioli
解决方法:
您可以在Fluent API中使用它:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasMany(p => p.Friends)
.WithOptional()
.Map(conf => conf.MapKey("FriendID"));
modelBuilder.Entity<Person>()
.HasOptional(p => p.Parent)
.WithMany()
.Map(conf => conf.MapKey("ParentID"));
}
我在这里假设关系是可选的. People表现在获得两个外键FriendID和ParentID.这样的事情应该适用于:
using (var context = new MyContext())
{
Person person = new Person() { Name = "Spock", Friends = new List<Person>()};
Person parent = new Person() { Name = "Sarek" };
Person friend1 = new Person() { Name = "Kirk" };
Person friend2 = new Person() { Name = "McCoy" };
person.Parent = parent;
person.Friends.Add(friend1);
person.Friends.Add(friend2);
context.People.Add(person);
context.SaveChanges();
// Load with eager loading in this example
var personReloaded = context.People
.Where(p => p.Name == "Spock")
.Include(p => p.Parent)
.Include(p => p.Friends)
.First();
}
标签:c,entity-framework,entity-framework-4,entity-framework-4-1,code-first 来源: https://codeday.me/bug/20190518/1128481.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。