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?
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