Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing entities pointed by foreign keys in Entity Framework

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.

like image 919
Ari Avatar asked Nov 21 '12 16:11

Ari


3 Answers

You can tell Entity Framework in include Photos when querying Cars.

var carList = CarEntities.Include(c => c.Photos).Where(...).ToList();
like image 120
ckal Avatar answered Nov 11 '22 07:11

ckal


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

like image 45
daehaai Avatar answered Nov 11 '22 05:11

daehaai


"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.

like image 40
Charlie Salts Avatar answered Nov 11 '22 05:11

Charlie Salts