![](/img/trans.png)
[英]Can I use an Interface with a Foreign Key in EF Core and set it as a foreign key using Fluent API?
[英]In EF Core, how do I configure the foreign key for reference owned types using Fluent API
在Company
实体中,我已将Address
作为引用拥有类型包含在内(以便Company
表将地址的属性包含为列)。 引用拥有的Address
通过持有作为Address
类的属性的外键CountryCode
包括Country
。 因此,我需要将此属性配置为外键。
当我使用属性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 中正确配置此引用拥有的类型关系?
您需要嵌套您拥有的实体。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.