none
One to One Relationship With Same Entity Type - FluentAPI RRS feed

  • Question

  • Hello

    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. 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. More or less like a husband and wife scenario.

    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

    builder.HasOne(p => p.Partner)
                .WithOne(p => p.Partner) // Not sure what to do here on the reverse since its same entity
                .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...

    Thursday, December 19, 2019 7:57 AM

All replies

  • Hi Godymn,
    According to my understanding, Partner is defined as a property of class Patient. So you can assign it directly.
    WithOne method is used to configure the one side of a one-to-many or one-to-one relationship.it is usually used in two or multiple entities
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, December 20, 2019 3:10 AM