In a Company entity I have included Address as a reference owned type (so that the Company table includes the properties of the address as columns). The reference owned Address includes Country by holding the foreign key CountryCode which is a property of the Address class. As such I need to configure this property as the foreign key.
When I use the attribute ForeignKey("Country") the migration is successful and the table is created with the correct column as FK: [Companies].[Address_CountryCode]. However I want to use the Fluent API for all my EF Core DbContext configurations. And this fails as the migration finds a conflict in ownership of Address.
class Company
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
public string Street { get; set; }
public string CountryCode { get; set; }
public Country Country { get; set; }
}
modelBuilder.Entity<Company>().OwnsOne<Address>(c => c.Address);
modelBuilder.Entity<Address>().HasOne<Country>(c => c.Country).WithMany().HasForeignKey(a => a.CountryCode);
Setting up the foreign key through Fluent API in this matter, fails with the following message:
The type 'Address' cannot be configured as non-owned because an owned entity type with the same name already exists.. Again, with the ForeignKey attribute it works as expected.
How do I configure this reference owned type relationship in Fluent API correctly?
You need to nest your owned entities.
modelBuilder.Entity<Company>().OwnsOne<Address>(c => c.Address, a => {
a.HasOne<Country>(c => c.Country).WithMany().HasForeignKey(a => a.CountryCode);
});
Reference: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#nested-owned-types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With