2012-01-31 44 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); 
} 
相關問題