In EF Core, how do I configure the foreign key for reference owned types using Fluent API

Viewed 1615

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?

1 Answers
Related