One to one relationship without reference property on one side

c# entity-framework-core

Question

I have the following construct; a person with an address (ownsone, sub-entity) and an address with a country (hasone, one-to-one)

public class Person
{
     public Guid Id {get; set;}
     public string Name {get; set;}
     public Address Address {get; set;}
}

public class Address 
{
     public Guid Id {get; set;}
     public Guid CountryId {get; set;}
     public Country Country {get; set;}
}

public class Country
{
     public Guid Id {get; set;}
     public string CountryCode {get; set;}
}

public class EntityConfiguration<Person> where Person : class
{
     public void Configure(EntityBuilder<Person> builder)
     {
         builder.OwnsOne(p => p.Address, addressBuilder => 
         addressBuilder.HasOne(address => address.Country).WithOne();
     }
}

When I run Add-Migration I get a block of code for each entity which owns one address. With auto-generated keys and so on. But I want to specify the relation explicitly with HasForeignKey. How to do this?

1
1
12/8/2017 9:16:07 AM

Popular Answer

EF Core provides 2 fluent APIs for one-to-one relationships - HasForeignKey and HasPrincipalKey.

The main difference with one-to-many APIs is that you need to explicitly provide the generic type argument, because the principal and dependent end of the relationship cannot be determined by the HasOne / WithOne calls (for one-to-many the one is always the principal and many is the dependent). The navigation properties in this case doesn't matter:

addressBuilder.HasOne(address => address.Country)
   .WithOne()
   .HasForeignKey<Address>(address => address.CountryId)

Reference: Relationships

3
12/8/2017 9:29:58 AM


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