首页 > 解决方案 > 在 EF Core 中,如何使用 Fluent API 为引用拥有的类型配置外键

问题描述

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

当我使用该属性ForeignKey("Country")时,迁移成功,并且使用正确的列创建表 FK: [Companies].[Address_CountryCode]。但是,我想将 Fluent API 用于我的所有 EF Core DbContext 配置。这失败了,因为迁移发现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);    

在这件事中通过 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 中正确配置此引用拥有的类型关系?

标签: c#entity-framework-core

解决方案


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

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

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


推荐阅读