[英]one to one multiple foreign key from same table EF Core
Stuck on write code for table relation below :坚持为下面的表关系编写代码:
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; }
}
I use Fluent API :我使用 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);
when i build, it getting error当我构建时,它收到错误
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.
there are several references for similar problem :类似问题有几个参考:
but those are for one-to-many relationship.但那些是一对多的关系。
*sorry for my bad english *对不起,我的英语不好
I had a similar situation in my project, and this is what I ended up doing:我在我的项目中遇到了类似的情况,这就是我最终要做的:
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; }
}
so PersonModel
would have two foreign keys to PersonDetailModel
.所以
PersonModel
会有两个PersonDetailModel
外键。 I am using ForeignKey
attribute to explicitly tell EF which foreign key belongs to which relationship - if you use the Foreignkey
attribute, you won't need the Fluent API Configurations...我使用
ForeignKey
属性来明确告诉 EF 哪个外键属于哪个关系 - 如果您使用Foreignkey
属性,则不需要 Fluent API 配置...
The above code will build you a PersonModel
table in the DB, with PersonId
and MateId
columns as foreign key.上面的代码将在数据库中为您构建一个
PersonModel
表,其中PersonId
和MateId
列作为外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.