Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
Superman.Lopez Avatar asked Nov 07 '25 22:11

Superman.Lopez


1 Answers

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

like image 87
ESG Avatar answered Nov 09 '25 11:11

ESG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!