c# – 实体框架代码优先 – 将两个字段联合成一个集合

前端之家收集整理的这篇文章主要介绍了c# – 实体框架代码优先 – 将两个字段联合成一个集合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个型号和配置
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);
     }
 }

我得到这个类型是初始的错误.

Schema specified is not valid. Errors: (151,6) : error 0040: Type
Person_Father is not defined in namespace ExamModel (Alias=Self).

有没有办法通过两个属性(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);
     }
 }
原文链接:https://www.f2er.com/csharp/98642.html

猜你在找的C#相关文章