本文介绍了实体框架代码第一 - 联盟两个字段成一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个型号和配置

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

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

and i get this error where the type is initial.

模式是无效的。错误:(151,6):错误0040:。键入
Person_Father没有命名空间ExamModel(别名=自)定义的

有没有一种方法来映射由两个属性(motherId和fatherId)童车属性?

Is there a way to map Childs property by both properties (motherId and fatherId)?

推荐答案

它无法将两个导航属性映射到一个单一的集合属性。它看起来太荒唐了,但你必须有两个集合属性。

Its not possible to map two navigational properties to a single collection property. It looks ridicules but you have to have two collection properties

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

这篇关于实体框架代码第一 - 联盟两个字段成一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 02:40