简体   繁体   English

列出实体框架中外键指向的实体

[英]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. 每张照片都有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? 如何在1 db查询的Entity Framework中执行此操作? 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. 我想,EF会为每辆车单独进行数据库查询。

在查询汽车时,您可以在实体框架中包含照片。

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), ckal的答案非常接近,除非最后使用包括在内,否则EF可能并不总是包含它(暂时不能回想起原因),

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

Edit: Here's the reason... Entity Framework Include() is not working 编辑:这是原因...... 实体框架Include()不起作用

"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”对象时,我使用了这种技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM