继续为下面的表关系写代码:
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.
有几个类似问题的参考文献:
但是这些是一对多关系。
*对不起我的英语不好
答案 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
表,并以PersonId
和MateId
列作为外键。