简体   繁体   English

具有相同实体类型的一对一关系 - FluentAPI

[英]One to One Relationship With Same Entity Type - FluentAPI

Just a little concern on how to configure EF for a one to one relationship with same Entity which is a rare case for me.只是有点担心如何为与同一实体的一对一关系配置 EF,这对我来说是一种罕见的情况。 This requirement came to me and i was a bit skeptical on how to model this.我想到了这个要求,我对如何对此建模持怀疑态度。

Here is the scenario,这是场景,

A patient can have one partner and a partner can only belong to one patient.一个病人可以有一个伙伴,一个伙伴只能属于一个病人。 A partner is also a patient.伴侣也是患者。

I have my model like this;我有这样的模型;

 public class Patient
 {
    public long Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public EGender Gender { get; set; }

    public DateTime DateOfBirth { get; set; }

    public DateTime CreatedAt { get; set; }

    public long PartnerId { get; set; }

    public Patient Partner { get; set; }

    public EPatientType PatientType { get; set; }
 }

And my FluentAPI config like this, but not sure i got this right我的 FluentAPI 配置是这样的,但不确定我做对了

      builder.HasOne(p => p.Partner)
            .WithOne(p => p.Partner) // Not sure what to do here
            .IsRequired(false)
            .HasForeignKey<Patient>(p => p.PartnerId)
            .OnDelete(DeleteBehavior.Restrict);

Any idea on how to model this on fluentAPI or how to proceed is appreciated...任何关于如何在 fluentAPI 上对此建模或如何进行的想法表示赞赏......

[索引(“IX_UniqueParentId”,1,IsUnique = true)]

public long? PartnerId { get; set; }

Try to use:尝试使用:

builder.HasOne(p => p.Partner)
       .WithOne()
       .IsRequired(false)
       .HasForeignKey<Patient>(p => p.PartnerId);

It worked for me.它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM