簡體   English   中英

實體框架代碼優先 - 將兩個字段聯合成一個集合

[英]entity framework code first - Union of the two fields into one collection

我有這個型號和配置

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:在名稱空間ExamModel(Alias = Self)中未定義類型Person_Father。

有沒有辦法通過兩個屬性(motherId和fatherId)映射Childs屬性?

無法將兩個導航屬性映射到單個集合屬性。 它看起來很嘲笑,但你必須有兩個集合屬性

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);
     }
 }

謝謝你,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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM