Listing entities pointed by foreign keys in Entity Framework

c#, database, entity-framework, performance

Solution

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

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

Problem

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.

Original source

Related problems