EF Core One to One or Zero Relationship

.net-core ef-core-2.2 entity-framework-core

Question

I have Person and Address. Address is optional. Please see below code

class Person
{
    [Key]
    public int PersonID { get; set; }
    public string Name { get; set; }

    public Address Address { get; set; }

}

class Address
{
    [Key, ForeignKey("Person")]
    public int PersonID { get; set; }

    public string City { get; set; }
}

Registration code is below:

modelBuilder.Entity<Address>(entity =>
            {
                entity.HasKey(z => z.PersonID);
                entity.HasOne(p => p.Person)
                     .WithOne(a => a.Address)
                     .HasForeignKey<Person>(a => a.PersonId);
            });

How should i change mapping to make Address optionable?

1
12
3/4/2019 2:50:01 PM

Accepted Answer

Here

.HasForeignKey<Person>(a => a.PersonId)

you are telling EF that Person.PersonId will be a FK (foreign key) to Address, i.e. Person is dependent and is referencing the principal Address.

It should be other way around:

.HasForeignKey<Address>(a => a.PersonId)

This way, Person (the principal) will have 0..1 Address, and Address (the dependent) will have 1 Person (because the PersionId is both PK and FK).

This is called Shared Primary Key association and is the standard (and default) way of modelling one to zero or one relationship in EF Core.

For more info, see Relationships.

20
3/4/2019 2:49:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow