我试图在EF6中为以下自引用人类建模。如何使用实体框架正确建模自引用多父项关系
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int? MotherId { get; set; }
public Person Mother { get; set; }
public int? FatherId { get; set; }
public Person Father { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
而且我的DbContext是这样的:
public virtual DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(m => m.Mother)
.WithMany(c => c.Children)
.HasForeignKey(m => m.MotherId);
modelBuilder.Entity<Person>()
.HasOptional(f => f.Father)
.WithMany(c => c.Children)
.HasForeignKey(f => f.FatherId);
}
当尝试使用下面的代码的人添加到数据库:
db.People.Add(new Person { Name = "Jane Doe" });
我得到这个错误:
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: Sequence contains no matching element
这个错误是什么意思,我该如何纠正?另外,有没有更好的方法来建模这个对象(例如:使用母亲的子类:人和父:人)?
你如何指定FK? – Ewan
您不需要 - 默认情况下,EF使用相关实体的PK,按照惯例,这是名为ID或ClassNameID的道具。 –