Is there a way to decorate your POCO classes to automatically eager-load child entities without having to use Include()
every time you load them?
Say I have a Class Car, with Complex-typed Properties for Wheels, Doors, Engine, Bumper, Windows, Exhaust, etc. And in my app I need to load my car from my DbContext 20 different places with different queries, etc. I don't want to have to specify that I want to include all of the properties every time I want to load my car.
I want to say
List<Car> cars = db.Car
.Where(x => c.Make == "Ford").ToList();
//NOT .Include(x => x.Wheels).Include(x => x.Doors).Include(x => x.Engine).Include(x => x.Bumper).Include(x => x.Windows)
foreach(Car car in cars)
{
//I don't want a null reference here.
String myString = car.**Bumper**.Title;
}
Can I somehow decorate my POCO class or in my OnModelCreating()
or set a configuration in EF that will tell it to just load all the parts of my car when I load my car? I want to do this eagerly, so my understanding is that making my navigation properties virtual is out. I know NHibernate supports similar functionality.
Just wondering if I'm missing something. Thanks in advance!
Cheers,
Nathan
I like the solution below, but am wondering if I can nest the calls to the extension methods. For example, say I have a similar situation with Engine where it has many parts I don't want to include everywhere. Can I do something like this? (I've not found a way for this to work yet). This way if later I find out that Engine needs FuelInjectors, I can add it only in the BuildEngine and not have to also add it in BuildCar. Also if I can nest the calls, how can I nest a call to a collection? Like to call BuildWheel() for each of my wheels from within my BuildCar()?
public static IQueryable<Car> BuildCar(this IQueryable<Car> query) {
return query.Include(x => x.Wheels).BuildWheel()
.Include(x => x.Doors)
.Include(x => x.Engine).BuildEngine()
.Include(x => x.Bumper)
.Include(x => x.Windows);
}
public static IQueryable<Engine> BuildEngine(this IQueryable<Engine> query) {
return query.Include(x => x.Pistons)
.Include(x => x.Cylendars);
}
//Or to handle a collection e.g.
public static IQueryable<Wheel> BuildWheel(this IQueryable<Wheel> query) {
return query.Include(x => x.Rim)
.Include(x => x.Tire);
}
Here is another very similar thread in case it is helpful to anyone else in this situation, but it still doesn't handle being able to make nexted calls to the extension methods.
Entity framework linq query Include() multiple children entities
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…