'Check if Entity is exists in deeply related Entity
I am trying to check wether an Entity exists in a deeply related Entity. Here is an picture of my model and the code I am using for the relationships.
Code
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; }
}
I have a list of TrainActivities and for each TrainActivity I want to check if the TrainActivity exists in a TimeTable object with TimeTableType==Type1. If so, I want to keep the TrainActivity in the list else I want to remove it from the list.
What is the easiest way to do this? I can't do this:
trainActivity.Train.TrainSerie.TimeTable.TimeTableType == TimeTableType.Type1
Because each reference navigation property is null.
Solution 1:[1]
I don't know what database you use and how you keep the enum in the table property TimeTable.TimeTableType, but if you change it to string you can try something like this
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Darkk L |

