entity-framework - 在 EF Core 2.0 中使用 OwnsOne 方法映射属性

标签 entity-framework .net-core entity-framework-core

我正在尝试将 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/

相关文章:

c# - 基于 EF 4.0 泛型的继承

c# - 我的 NuGet 包与 .NET Core 兼容吗?

c# - 如何获取当前用户的SelectList

c# - Entity Framework 核心 : Challenge Modeling Product Variants Database Design with Many to Many

c# - EF 7(核心)。像 AddTransient 一样创建 DBContext

c# - Entity Framework : map varchar to DateTime property

asp.net-mvc - 将 LINQ to EF 投影到 View 模型时出现异常。获取 "only parameterless constructor and initializers"异常

entity-framework - LINQ 到实体 4 : Query with calculation in where clause

javascript - .NET Core 查看页面的值到 JavaScript 数组

.net-core - Environment.Exit 后托管服务未终止