来自同一表EF Core的一对一多个外键

时间:2018-11-13 06:41:24

标签: entity-framework asp.net-core entity-framework-core

继续为下面的表关系写代码:

 public class PersonModel
{
    public int ID { get; set; }
    public string Name{ get; set; }
    public string Address{ get; set; }
    public DateTime? DateofBirth{ get; set; }
    public GenderEnum Gender{ get; set; }

    public PersonDetailModel PersonDetail { get; set; }
    public PersonDetailModel PersonDetailforMate { get; set; }

}

public class PersonDetailModel
{
    public int ID { get; set; }
    public int PersonID { get; set; }
    public int? MateID { get; set; }
    public string PhoneNumber{ get; set; }
    public string OfficeAddress{ get; set; }
    public MarriageStatusEnum MarriageStatus{ get; set; }

    public PersonModel Person { get; set; }
    public PersonModel PersonforMate { get; set; }

}

我使用Fluent API:

modelBuilder.Entity<PersonModel>()
            .HasOne(d => d.PersonDetailModel)
            .WithOne(p => p.PersonModel)
            .HasForeignKey<PersonDetailModel>(d => d.PersonID);

modelBuilder.Entity<PersonDetailModel>()
            .HasOne(d => d.PersonModel)
            .WithOne(p => p.PersonDetailModel)
            .HasForeignKey<PersonDetailModel>(d => d.MateID);

建造时会出现错误

Cannot create a relationship between 'PersonModel.PersonDetailforMate' and 'PersonDetailModel.Person', because there already is a relationship between 'PersonModel.PersonDetail' and 'PersonDetailModel.Person'. Navigation properties can only participate in a single relationship.

有几个类似问题的参考文献:

但是这些是一对多关系。

*对不起我的英语不好

1 个答案:

答案 0 :(得分:0)

我的项目中也有类似情况,这就是我最终要做的事情:

public class PersonModel
{
    public int ID { get; set; }
    public string Name{ get; set; }
    public string Address{ get; set; }
    public DateTime? DateofBirth{ get; set; }
    public GenderEnum Gender{ get; set; }

    public int PersonID { get; set; }
    [ForeignKey("PersonID ")]
    public PersonDetailModel PersonDetail { get; set; }

    public int? MateID { get; set; }
    [ForeignKey("MateID")]
    public PersonDetailModel PersonDetailforMate { get; set; }
}

public class PersonDetailModel
{
    public int ID { get; set; }
    public string PhoneNumber{ get; set; }
    public string OfficeAddress{ get; set; }
    public MarriageStatusEnum MarriageStatus{ get; set; }
}

因此PersonModel将具有两个指向PersonDetailModel的外键。我正在使用ForeignKey属性来明确告诉EF哪个外键属于哪个关系-如果使用Foreignkey属性,则不需要Fluent API配置...

以上代码将在数据库中建立一个PersonModel表,并以PersonIdMateId列作为外键。