我正在尝试将 EF 6 项目迁移到 EF Core 2.0。 我想强调的是,我不允许更改数据库结构中的任何内容 - 必须与 EF 6 项目完全相同。
我有以下实体:
abstract class Vehicle { ... }
abstract class Car : Vehicle
{
public Dimension Dimensions { get; set; }
}
class Audi : Car { ... }
class Mazda : Car { ... }
class Dimension
{
public double Width { get; set; }
public double Height { get; set; }
}
表映射如下:
public VehicleMap(EntityTypeBuilder<Vehicle> entityBuilder)
{
entityBuilder.ToTable("Vehicles");
entityBuilder.HasKey(_ => _.Id);
entityBuilder.HasDiscriminator<string>("Type").HasValue<Truck>(nameof(Truck));
}
public CarMap(EntityTypeBuilder<Car> entityBuilder)
{
entityBuilder.HasDiscriminator<string>("Type")
.HasValue<Mazda>(nameof(Mazda))
.HasValue<Audi>(nameof(Audi));
**entityBuilder.OwnsOne(_ => _.Dimensions);**
}
我遇到的问题是关于 Car
抽象类中定义的 Dimensions
属性。我想使用 OwnsOne
方法对其进行映射,使其所有类属性都定义在同一个表中。
我收到以下错误:
Cannot use table 'Vehicles' for entity type 'Car.Dimensions#Dimension' since it has a relationship to a derived entity type 'Car'. Either point the relationship to the base type 'Vehicle' or map 'Car.Dimensions#Dimension' to a different table.
知道如何在 EF Core 2.0 中解决它吗?
最佳答案
The
Dimension
known as ValueObject. The best practice for this type of objects is here.
要首先在您的上下文中实现此对象,您应该在基表中定义它,因为当您使用此配置创建数据库时,您只有一个名为 Vehicles
的表和名为的鉴别器列类型
。
如错误所述:
Either point the relationship to the base type 'Vehicle'
我们应该在基类中定义Dimension
。
abstract class Vehicle
{
public Dimension Dimensions { get; private set; }
}
表映射:
public VehicleMap(EntityTypeBuilder<Vehicle> entityBuilder)
{
entityBuilder.ToTable("Vehicles");
entityBuilder.HasKey(_ => _.Id);
entityBuilder.HasDiscriminator<string>("Type").HasValue<Truck>(nameof(Truck));
// Here
entityBuilder.OwnsOne(p => p.Dimensions);
}
关于entity-framework - 在 EF Core 2.0 中使用 OwnsOne 方法映射属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46017372/