I want to retrieve some data and use it in a new form that fits my use case. Because of the amount of data aswell as the data model eager loading is the prefered and faster way. Through this i stumbled upon something I can't explain.
The following is a simplified example:
Enitities
public class Car
{
public int Id { get; set; }
public bool Deleted { get; set; }
public string Name { get; set; }
public virtual Engine Engine { get; set; }
public virtual List<Tire> Tires { get; set; }
}
public class Engine
{
public int Id { get; set; }
public string Name { get; set; }
public int PS { get; set; }
}
public class Tire
{
public int Id { get; set; }
public string Name { get; set; }
public int Profile { get; set; }
}
Code
var cars = DbContext.Current.Cars
.Include(c => c.Engine)
.Include(c => c.Tires)
.Where(c => !c.Deleted)
.Select(c => new {
Car = c,
TireIds = c.Tires.Select(t => t.Id)})
.ToList();
When I am trying to access the Engine later on it is not included and needs to be reloaded from the database which is expensive. Nevertheless the tires-Collection is present.
If I am doing the following, the engine is included later on.
Code
var cars = DbContext.Current.Cars
.Include(c => c.Engine)
.Include(c => c.Tires)
.Where(c => !c.Deleted)
.ToList();
var carsAndTires = cars.Select(c => new { Car = c, TireIds = c.Tires.Select(t => t.Id)}).ToList();