I have two Entities, let's say Car and Photo. Each photo has foreign key to Car, so each car has set of its photos.
I want to list some subset of cars and for each listed car I want to list all of each photos.
How can I do this in Entity Framework with 1 db query? I know from the beginning that I would need photos.
My code for now look like:
var carList = CarEntities.Where(...).ToList();
foreach(var car in carList){
var photoList = car.Photos.ToList();
}
I think, EF would do separately db query for each car.
You can tell Entity Framework in include Photos when querying Cars.
var carList = CarEntities.Include(c => c.Photos).Where(...).ToList();
ckal's answer is pretty close except use include in the end otherwise EF may not always include it (cant recall exact reason at the moment),
var carList = CarEntities.Where(...).Include(c => c.Photos).ToList();
Edit: Here's the reason... Entity Framework Include() is not working
"Select new" is what you likely want to do. Create a new class called CarWithPhotos
and use that to return a set of results:
var carWithPhotos = from car in CarEntities
where (...)
select new CarWithPhotos(car, car.Photos.ToList());
As I understand it, this compiles to one a single database trip, which I think is what you're after.
Edit: I've used this technique when the objects I'm querying are large and I don't always want to retrieve an entire "Car" object for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With