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.
我有两个实体,比方说汽车和照片。每张照片都有Car的外键,所以每辆车都有一套照片。
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.
如何在1 db查询的Entity Framework中执行此操作?我从一开始就知道我需要照片。
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.
我想,EF会为每辆车单独进行数据库查询。
3 个解决方案
#1
5
You can tell Entity Framework in include Photos when querying Cars.
在查询汽车时,您可以在实体框架中包含照片。
var carList = CarEntities.Include(c => c.Photos).Where(...).ToList();
#2
4
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),
ckal的答案非常接近,除非最后使用包括在内,否则EF可能并不总是包含它(暂时不能回想起原因),
var carList = CarEntities.Where(...).Include(c => c.Photos).ToList();
Edit: Here's the reason... Entity Framework Include() is not working
编辑:这是原因...实体框架Include()不起作用
#3
1
"Select new" is what you likely want to do. Create a new class called CarWithPhotos
and use that to return a set of results:
“选择新”是您可能想要做的。创建一个名为CarWithPhotos的新类,并使用它来返回一组结果:
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.
编辑:当我查询的对象很大并且我并不总是想要检索整个“Car”对象时,我使用了这种技术。
#1
5
You can tell Entity Framework in include Photos when querying Cars.
在查询汽车时,您可以在实体框架中包含照片。
var carList = CarEntities.Include(c => c.Photos).Where(...).ToList();
#2
4
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),
ckal的答案非常接近,除非最后使用包括在内,否则EF可能并不总是包含它(暂时不能回想起原因),
var carList = CarEntities.Where(...).Include(c => c.Photos).ToList();
Edit: Here's the reason... Entity Framework Include() is not working
编辑:这是原因...实体框架Include()不起作用
#3
1
"Select new" is what you likely want to do. Create a new class called CarWithPhotos
and use that to return a set of results:
“选择新”是您可能想要做的。创建一个名为CarWithPhotos的新类,并使用它来返回一组结果:
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.
编辑:当我查询的对象很大并且我并不总是想要检索整个“Car”对象时,我使用了这种技术。