c# – 使用Entity Framework实现双重自引用属性
作者:互联网
这段代码小规模地表示我的问题:
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