实体框架中数据建模和/或查询TPT模型的问题

本文关键字:TPT 查询 模型 问题 框架 数据 建模 实体 | 更新日期: 2023-09-27 18:13:30

我有一个抽象对象,其中有两个抽象对象列表。正在创建模型,数据库看起来很好,但是我无法进行我所期望的查询。

数据模型看起来像这样

public abstract class Vehicle
{
    protected Vehicle() 
    {
        this.CrashIncidents = new List<Incident>();
        this.SpeedingIncidents = new List<Incident>();
    }
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Incident> CrashIncidents { get; set; }
    public virtual ICollection<Incident> SpeedingIncidents { get; set; }
}
public class Car : Vehicle
{
    public string Color { get; set; }
}
public class Lorry : Vehicle
{
    public int MaxCarryWeight { get; set; }
}
public abstract class Incident
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Incident> VehicleCrashIncidents { get; set; }
    public virtual ICollection<Incident> VehicleSpeedingIncidents { get; set; }
}
public class CrashIncident : Incident
{
    public string Severity { get; set; }
}
public class SpeedingIncident : Incident
{
    public string MPHRegistered { get; set; }
}

任何my OnModelCreating在Context类中看起来像这样

modelBuilder.Entity<Vehicle>().HasMany<Incident>(o => o.CrashIncident).WithMany(a => a.VehicleCrashIncidents).Map(m => m.MapLeftKey("Id").MapRightKey("VehicleCrashIncidentId").ToTable("VehicleCrashIncident"));
modelBuilder.Entity<Vehicle>().HasMany<Incident>(o => o.SpeedingIncident).WithMany(a => a.VehicleSpeedingIncidents).Map(m => m.MapLeftKey("Id").MapRightKey("VehicleSpeedingIncidentId").ToTable("VehicleSpeedingIncident"));
modelBuilder.Entity<CrashIncident>().ToTable("CrashIncident");
modelBuilder.Entity<SpeedingIncident>().ToTable("SpeedingIncident");

然而,我无法查询这样的事情:获得所有车辆(或具体类)与事件的严重性X,即像这样的东西:

var problems = context.Vehicle.Where(x => x.CrashIncidents.Any(y => y.Severity == "High");

问题是查询的最后一部分(在y部分),我无法选择严重性,只有抽象类的属性可见。我无法确定(因此谷歌),如果问题在于我的数据模型或与我的查询。

实体框架中数据建模和/或查询TPT模型的问题

受此启发:

实体框架6中多对多关系+ TPH继承的问题

我让这个工作。我从模型的抽象部分中删除了特定的虚拟部分,如下所示:

public abstract class Vehicle
{
    protected Vehicle() 
    {
        this.Incidents= new List<Incident>();
    }
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Incident> Incidents{ get; set; }
}

并将导航属性改为

public abstract class Incident
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Incident> VehicleIncidents { get; set; }
}
在OnModelCreating中,我可以删除两个"modelBuilder.Entity()"。HasMany"行。最后,我可以执行以下查询:
var problems = context.Vehicle.Where(x => x.Incidents.OfType<CrashIncidents>.Any(y => y.Severity == "High");

我必须承认我不确定我之前是否尝试过那个特定的查询,所以我不确定是否是我的数据模型中的变化允许我进行该查询,或者它一直是可能的,我只是不知道它。