实体框架代码前三个类中相同类型的导航属性

时间:2015-11-13 03:18:55

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

我为一个出生证书的类建模,所以我需要包含父亲,母亲和孩子的三种类型的属性。

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

这是我的班级BirthCertificate

    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的使用,所以这个模式如下所示:

  

无法确定之间关联的主要结束   类型'人物'和' BirthCertificate'。这个的主要目的   必须使用以下任一方式显式配置关联   关系流畅的API或数据注释。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您的反向属性使用是正确的,EF不知道哪个是已配置关系的主要结尾 - 也就是说,出生证明属于该人,还是该人属于出生证明? EF将使用它来确定插入顺序。通常它只使用任何具有可空FK的参与者,但你的两个FK都不可为空。

对导航属性使用数据注释[必需],或者使用流畅的API .HasRequiredPrincipal()。WithRequiredDependant();

答案 1 :(得分:0)

对于任何试图尝试与我相同的目标的人,我最终以这种方式解决了与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);
相关问题