2012-01-31 75 views
6

我有这个型号和配置实体框架代码第一 - 这两个领域的联合成一个集

public class Person 
{ 
    public int? FatherId { get; set; } 
    public virtual Person Father { get; set; } 
    public int? MotherId { get; set; } 
    public virtual Person Mother { get; set; } 
    public virtual List<Person> Childs { get; set; } 

} 
class PersonConfiguration : EntityTypeConfiguration<Person> 
{ 
    public PersonConfiguration() 
    { 
     HasOptional(e => e.Father).WithMany(e => e.Childs) 
       .HasForeignKey(e => e.FatherId); 
     HasOptional(e => e.Mother).WithMany(e => e.Childs) 
       .HasForeignKey(e => e.MotherId); 
    } 
} 

和我得到这个错误的类型为初始。

指定的模式无效。错误:(151,6):错误0040:类型 Person_Father未在名称空间ExamModel(Alias = Self)中定义。

有没有办法通过两个属性(motherId和fatherId)映射Childs属性?

回答

14

无法将两个导航属性映射到单个集合属性。它看起来嘲笑,但你必须有两个集合属性

public class Person 
{ 
    public int? FatherId { get; set; } 
    public virtual Person Father { get; set; } 
    public int? MotherId { get; set; } 
    public virtual Person Mother { get; set; } 
    public virtual List<Person> ChildrenAsFather { get; set; } 
    public virtual List<Person> ChildrenAsMother { get; set; } 
} 

class PersonConfiguration : EntityTypeConfiguration<Person> 
{ 
    public PersonConfiguration() 
    { 
     HasOptional(e => e.Father).WithMany(e => e.ChildrenAsFather) 
       .HasForeignKey(e => e.FatherId); 
     HasOptional(e => e.Mother).WithMany(e => e.ChildrenAsMother) 
       .HasForeignKey(e => e.MotherId); 
    } 
} 
2

谢谢你,Eranga,你的回答正是我所需要的!

此外,如果有人使用该方法而不是Eranga使用的配置方法,则此处为modelBuilder代码。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Person>(). 
    HasKey(i => i.PersonId); 

    modelBuilder.Entity<Person>(). 
    HasOptional(f => f.Father). 
    WithMany(f => f.ChildrenAsFather). 
    HasForeignKey(f => f.FatherId); 

    modelBuilder.Entity<Person>(). 
    HasOptional(m => m.Mother). 
    WithMany(m => m.ChildrenAsMother). 
    HasForeignKey(m => m.MotherId); 
} 
相关问题