c# - 在 Entity Framework 中使用TPT设计的多级继承

标签 c# entity-framework multiple-inheritance table-per-type

我想在 EF 中实现以下模型作为 TPT 设计。

enter image description here

我的代码如下:

基础模型

public abstract class Product
{
    public int Id { get; set; }
    public DateTime ProductionDate { get; set; }
}

车型

public abstract class Car : Product
{
    public string ChassisNumber { get; set; }
    public string DriverName { get; set; }
}

[Table("TeslaCars")]
public class TeslaCar : Car
{
    public string Battery { get; set; }
    public int Temperature { get; set; }
}

[Table("PorscheCars")]
public class PorscheCar : Car
{
    public int FuelTank { get; set; }
}

摩托车型号

public abstract class Motorcycle : Product
{
    public string RiderName { get; set; }
    public bool IsRacing { get; set; }
}

[Table("CrossMotorcycles")]
public class CrossMotorcycle : Motorcycle
{
    public int MaximumJump { get; set; }
}

[Table("KipsMotorcycles")]
public class KipsMotorcycle : Motorcycle
{
    public long MaximumSpeed { get; set; }
}

但问题是,创建表后,仅进行 TPT 设计的最后一步,并创建 TPH 设计之上的层。

我的代码输出如下表: enter image description here

我应该如何修改代码以遵循各级表的 TPT 设计? 在最终输出中,我需要制作如下表格:

enter image description here

最佳答案

我终于得到答案了!

在本例中,我需要将汽车型号摩托车型号分别放在不同的表中,但上面的代码是默认使用TPH设计的。

所以我们必须这样更改代码:

基础模型

public abstract class Product
{
    public int Id { get; set; }
    public DateTime ProductionDate { get; set; }
}

车型

[Table("Cars")]
public abstract class Car : Product
{
    public string ChassisNumber { get; set; }
    public string DriverName { get; set; }
}

[Table("TeslaCars")]
public class TeslaCar : Car
{
    public string Battery { get; set; }
    public int Temperature { get; set; }
}

[Table("PorscheCars")]
public class PorscheCar : Car
{
    public int FuelTank { get; set; }
}

摩托车型号

[Table("Motorcycles")]
public abstract class Motorcycle : Product
{
    public string RiderName { get; set; }
    public bool IsRacing { get; set; }
}

[Table("CrossMotorcycles")]
public class CrossMotorcycle : Motorcycle
{
    public int MaximumJump { get; set; }
}

[Table("KipsMotorcycles")]
public class KipsMotorcycle : Motorcycle
{
    public long MaximumSpeed { get; set; }
}

关于c# - 在 Entity Framework 中使用TPT设计的多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59986638/

相关文章:

asp.net - 添加标签来讨论 Entity Framework 中的多对多关系

c# - 将 EF 模型从 SSCE 4.0 切换到 SQL Server 2008 R2

c++ - C++中的继承构造函数

c# - Lambda 函数中的 If 语句?

c# - 使用 Parallel.ForEach 在最小值中选择最小值

c# - 如何在 LINQ to Entities 中为 Entity Framework 对象使用谓词

c# - 我可以避免对简单的 Linq to Entities 投影进行嵌套 SQL 查询吗?

c# - 扩展方法的继承

python - 用多重继承调用父类__init__,正确的方法是什么?

c# - 允许 XSD 日期元素为空字符串