【发布时间】:2021-01-29 22:21:41
【问题描述】:
我有 2 个实体,它们之间的关系是 1-0..1,但是对生成的数据库架构的外观有限制。
所以 1 Vehicle 到 0 或 1 RecVehicle 实体
我需要能够拥有从 Vehicle 到 RecVehicle 的导航属性,但没有用于具有 FK 到 RecVehicle 的 Vehicles 表的数据库架构。 RecVehicle 表的 PK 应该是它所关联的 Vehicle 实体的 Id。
我们首先使用 EF 代码
public class Vehicle
{
[Key]
public int Id { get; set; }
public virtual RecVehicle RecVehicle { get; set; } // Need to be able to use as navigation
}
public class RecVehicle
{
[Key]
public int VehicleId { get; set; }
[ForeignKey("VehicleId")]
public Vehicle Vehicle { get; set; }
}
生成的架构需要是这样的:
车辆 [ Id(int, pk, not null), ...]
RecVehicles [ VehicleId(int, pk, fk, not null), ...]
最初我尝试过这样的事情:
public class Vehicle
{
[Key]
public int Id { get; set; }
[InverseProperty("Vehicle")]
public virtual RecVehicle RecVehicle { get; set; } // Need to be able to use as navigation
}
但这会导致此异常:
无法确定类型“Contract.Entities.Vehicle”和“Contract.Entities.RecVehicle”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。
我不确定要设置哪些流畅的 API 关系才能使这项工作正常工作,也不确定要使这项工作发挥作用的正确数据注释集,或者是否有可能。
推理
- 对数据库架构有严格限制的原因是我们的数据团队有一个我们无法更改的迁移/数据导入流程
- 我们有一个现有的代码库,它在许多地方(2 个团队,架构中不同步)使用导航属性,因此更改为在代码中使用查找需要在代码库中进行许多我们试图避免的更改。
【问题讨论】:
标签: c# .net entity-framework-6 ef-code-first .net-5