【发布时间】:2015-04-30 15:10:11
【问题描述】:
我正在尝试在实体框架中创建我认为可以称为可选 1:1 或可能 0..1:0..1 的关系。我希望能够在两个对象上都有导航属性。
我在现有数据库架构上使用 Entity Framework 的 Fluent API。
为简单起见,我们假设以下表格:
Car
Id int not null
Driver
Id int not null
CarId int null unique
使用以下类:
public class Car
{
public int Id { get; set; }
public virtual Driver { get; set; }
}
public class Driver
{
public int Id { get; set; }
public virtual Car { get; set; }
}
这个想法是 Car 和 Driver 可以相互独立存在,但是当 Driver 与 Car 关联时,它是一种互斥关联:Driver 只能与该 Car 关联,而该 Car 只能关联给那个司机。
我尝试了以下流畅的配置:
内部驱动配置:
HasOptional(d => d.Car)
.WithOptionalDependent()
.Map(d => d.MapKey("CarId"));
在汽车内部配置
HasOptional(c => cDriver)
.WithOptionalPrincipal()
.Map(d => d.MapKey("CarId"));
当我尝试这个时,我得到以下信息:
指定的架构无效。错误: (203,6):错误 0019:类型中的每个属性名称必须是唯一的。已定义属性名称“CarId”。
有没有办法在 Entity Framework 中使用两个对象的导航属性对此场景进行建模?
【问题讨论】:
-
为什么两者都有
d.MapKey("CarId")?一个不是CarId,另一个是DriverId? -
Car 表没有 DriverId 列。如果 Car 表中有 DriverId 列,它将允许指向与指向它的驱动程序不同的驱动程序的汽车 - 它是 1:1 或 0:0
标签: c# .net entity-framework