简体   繁体   English

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

[英]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).Company实体中,我已将Address作为引用拥有类型包含在内(以便Company表将地址的属性包含为列)。 The reference owned Address includes Country by holding the foreign key CountryCode which is a property of the Address class.引用拥有的Address通过持有作为Address类的属性的外键CountryCode包括Country 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] .当我使用属性ForeignKey("Country") ,迁移成功,并且使用正确的列作为 FK 创建了表: [Companies].[Address_CountryCode] However I want to use the Fluent API for all my EF Core DbContext configurations.但是,我想将 Fluent API 用于我所有的 EF Core DbContext 配置。 And this fails as the migration finds a conflict in ownership of Address .这失败了,因为迁移发现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.在这件事中通过 Fluent API 设置外键失败并显示以下消息: 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.同样,使用ForeignKey属性,它可以按预期工作。

How do I configure this reference owned type relationship in Fluent API correctly?如何在 Fluent API 中正确配置此引用拥有的类型关系?

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://docs.microsoft.com/en-us/ef/core/modeling/owned-entities#nested-owned-types参考: https : //docs.microsoft.com/en-us/ef/core/modeling/owned-entities#nested-owned-types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM