【问题标题】:Entity Framework Code First Three navigation properties of the same type in a classEntity Framework Code First 类中相同类型的三个导航属性
【发布时间】:2016-02-14 14:24:01
【问题描述】:

我正在为出生证明建模一个类,所以我需要包含三个 Person 类型的属性,分别代表父亲、母亲和孩子。

public class Person 
{
    public Guid PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName1 { get; set; }
    public string LastName2 { get; set; }
    [InverseProperty("Person")]
    public virtual BirthCertificate BirthCertificate { get; set; }
}

这是我的班级出生证明

    public class BirthCertificate : EntityBase
        {
            public Guid BirthCertificateId { get; set; }
            public string BirthCertificateNumber { get; set; }
            public Guid PersonId {get;set;}
            public Guid FatherPersonId {get;set;}
            public Guid MotherPersonId {get;set;}
            public Person Person { get; set; }
            public Person Father{ get; set; }
            public Person Mother { get; set; }

        }

我没有完全理解 InverseProperty Annotation 的使用,所以这个模式引发了以下异常:

无法确定之间关联的主体端 类型“Person”和“BirthCertificate”。这个的主要目的 关联必须使用任一显式配置 关系流式 API 或数据注释。

谁能帮帮我??

【问题讨论】:

    标签: entity-framework model-view-controller ef-code-first code-first


    【解决方案1】:

    对于任何试图尝试与我相同的目标的人,我最终以这种方式解决了与 Fluent 的关系:

    modelBuilder.Entity<BirthCertificate>()
                    .HasRequired(r => r.Person)      
                    .WithMany()                        
                    .HasForeignKey(r => r.PersonId)  
                    .WillCascadeOnDelete(false);
    
                modelBuilder.Entity<BirthCertificate>()
                    .HasRequired(r => r.Father)
                    .WithMany()
                    .HasForeignKey(r => r.FatherPersonId)
                    .WillCascadeOnDelete(false);
    
                modelBuilder.Entity<BirthCertificate>()
                    .HasRequired(r => r.Mother)
                    .WithMany()
                    .HasForeignKey(r => r.MotherPersonId)
                    .WillCascadeOnDelete(false);
    

    【讨论】:

      【解决方案2】:

      你的逆属性使用是正确的,EF不知道哪个是配置关系的主端——即出生证明是属于人的,还是人属于出生证明的? EF 将使用它来确定插入顺序。通常它只是使用具有可为空 FK 的任何参与者,但您的两个 FK 都不可为空。

      对导航属性使用数据注解 [Required],或者使用 fluent API .HasRequiredPrincipal().WithRequiredDependant();

      【讨论】:

      • 谢谢@DevilSuichiro,您的建议给了我解决问题的起点
      猜你喜欢
      • 2012-08-09
      • 1970-01-01
      • 2012-05-10
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多