加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:29:07 所属栏目:百科 来源:网络整理
导读:我有这个型号和配置 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 ListPerson Childs { get; se
我有这个型号和配置
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);
     }
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读