Listing objects specified by foreign keys in the Entity Framework

I have two entities, say, "Car and Photography." Each photo has a foreign car key, so each car has its own photos.

I want to list some subsets of cars, and for each listed car I want to list all the photos.

How to do this in Entity Framework with 1 db request? From the very beginning, I know that I need photographs.

Now my code is as follows:

var carList = CarEntities.Where(...).ToList(); foreach(var car in carList){ var photoList = car.Photos.ToList(); } 

I think EF will make a separate db request for each car.

+4
source share
3 answers

You can say that the Entity Framework will include Photos when requesting cars.

 var carList = CarEntities.Include(c => c.Photos).Where(...).ToList(); 
+5
source

Ckal's answer is pretty close, with the exception of using include at the end, otherwise EF may not always include it (at the moment it cannot type the exact reason),

 var carList = CarEntities.Where(...).Include(c => c.Photos).ToList(); 

Edit: Here is the reason ... Entity Framework Include () is not working

+3
source

โ€œChoose a new oneโ€ is what you most likely want to do. Create a new class called CarWithPhotos and use it to return a result set:

 var carWithPhotos = from car in CarEntities where (...) select new CarWithPhotos(car, car.Photos.ToList()); 

As I understand it, this compiles in one trip with one database, and I think you need it.

Edit: I used this technique when the objects I request are large, and I donโ€™t always want to get the entire โ€œCarโ€ object, for example.

+1
source

Source: https://habr.com/ru/post/1447541/


All Articles