在 EF Core 中,如何使用 Fluent API 为引用拥有的类型配置外键

Sup*_*pez 4 c# entity-framework-core

在我作为引用拥有的类型Company包含的实体中(以便表包含地址的属性作为列)。拥有的引用包括通过持有作为类的属性的外键。因此,我需要将此属性配置为外键。 AddressCompanyAddressCountryCountryCodeAddress

当我使用该属性时,ForeignKey("Country")迁移成功,并且使用正确的列创建表作为 FK: [Companies].[Address_CountryCode]。不过,我想对所有 EF Core DbContext 配置使用 Fluent API。由于迁移发现 . 的所有权存在冲突,因此此操作失败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; }
}
Run Code Online (Sandbox Code Playgroud)
modelBuilder.Entity<Company>().OwnsOne<Address>(c => c.Address);
modelBuilder.Entity<Address>().HasOne<Country>(c => c.Country).WithMany().HasForeignKey(a => a.CountryCode);    
Run Code Online (Sandbox Code Playgroud)

在这种情况下,通过 Fluent API 设置外键失败,并显示以下消息: The type 'Address' cannot be configured as non-owned because an owned entity type with the same name already exists.。同样,使用该ForeignKey属性它可以按预期工作。

如何在 Fluent API 中正确配置此引用所属类型关系?

ESG*_*ESG 5

您需要嵌套您拥有的实体。

modelBuilder.Entity<Company>().OwnsOne<Address>(c => c.Address, a => {
    a.HasOne<Country>(c => c.Country).WithMany().HasForeignKey(a => a.CountryCode);
});
Run Code Online (Sandbox Code Playgroud)

参考:https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#nested-owned-types