检查实体是否存在于深度相关的实体中

Check if Entity is exists in deeply related Entity

我正在尝试检查一个实体是否存在于一个密切相关的实体中。这是我的模型的图片和我用于关系的代码。

图片

代码

public class TimeTable
{
    [Key]
    public Guid TimeTableId { get; set; }

    public TimeTableType TimeTableType { get; set; }
    // one to many relation with TrainSeries
    public List<TrainSerie> TrainSeries { get; set; } = new List<TrainSerie>();

}

public enum TimeTableType
{
    Type1,
    Type2
}

public class TrainSerie
{
    [Key]
    public Guid TrainSerieId { get; set; }

    // one to many with Train
    public List<Train> Trains { get; set; } = new List<Train>();

    // Many to one with TimeTable
    public Guid TimeTableId { get; set; }
    public TimeTable TimeTable { get; set; }
}

public class Train
{
    [Key]
    public Guid TrainId { get; set; }

    public TrainType TrainType { get; set; }

    // one to many with TrainActivity
    public List<TrainActivity> TrainActivities { get; set; } = new List<TrainActivity>();

    // many to one with TrainSeries
    public Guid TrainSerieId { get; set; }
    public TrainSerie TrainSerie { get; set; }
}

public class TrainActivity
{
    [Key]
    public Guid TrainActivityId { get; set; }

    public ActivityType Act`enter code here`ivityType { get; set; }

    // many to one with TrainStation
    public Guid TrainStationId { get; set; }
    public TrainStation TrainStation { get; set; }

    // many to one with Train
    public Guid TrainId { get; set; }
    public Train Train { get; set; }

}

我有一个 TrainActivities 列表,对于每个 TrainActivity,我想检查 TrainActivity 是否存在于 TimeTableType==Type1 的 TimeTable 对象中。如果是这样,我想将 TrainActivity 保留在列表中,否则我想将其从列表中删除。

最简单的方法是什么?我不能这样做:

trainActivity.Train.TrainSerie.TimeTable.TimeTableType == TimeTableType.Type1

因为每个引用导航属性都是空的。

我不知道您使用的是什么数据库以及如何将枚举保存在 table 属性 TimeTable.TimeTableType 中,但是如果您将其更改为字符串,您可以尝试类似这个

public class TimeTable
{
    [Key]
    public Guid TimeTableId { get; set; }

    public string TimeTableType { get; set; }
    // one to many relation with TrainSeries
    public List<TrainSerie> TrainSeries { get; set; } = new List<TrainSerie>();

}

//result will be a list of TrainActivities with all properties loaded and only with TimeTableType = Type1
var result = dBcontext.TrainActivities
                .Include(x => x.Train)
                .ThenInclude(x => x.TrainSerie)
                .ThenInclude(x => x.TimeTable)
                .Where(x => x.Train.TrainSerie.TimeTable.TimeTableType == "Type1")
                .ToList();