c# - 在 EF Core 中,如何使用 Fluent API 为引用拥有的类型配置外键
问题描述
在Company
我Address
作为引用拥有的类型包含的实体中(以便该Company
表包含地址的属性作为列)。拥有的引用Address
包括通过持有作为类属性的Country
外键。因此,我需要将此属性配置为外键。 CountryCode
Address
当我使用该属性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
推荐阅读
- javascript - HTML/Javascript - 将用户输入添加为 JSON 对象
- spring-integration - 拆分器在异常期间中止,不处理后续消息
- sql-server - 无法在 Apache Superset 0.24 中添加数据库
- session - 使用带有会话变量的 servlet 过滤器
- php - 路线 [companies.show] 未定义
- mysql - 如何在表中插入数据时添加当前日期时间
- labview - LabVIEW:绘制波形图会导致内存泄漏
- java - 按下后退按钮后主要活动不回来
- oracle - 在 Netscape 浏览器中最大化 oracle 10g 表单的视图
- html - CSS:父元素底部的项目