[英]Entity Framework 4 - Query parent table and eager load 1 (single) child record
Can't seem to find a good way to search for this online. 似乎无法找到一种在线搜索的好方法。 I'm trying to get all parent records (cars) from a database and I want to include only 1 single child item (image) either in the original query or in a separate query run immediately after the first one so that the full results come back in a single result set.
我正在尝试从数据库中获取所有父记录(汽车),并且我想在原始查询中或在第一个之后立即在单独的查询中仅包含1个子项(图像),以便完整的结果来回到单个结果集中。
I have a database with a CAR table and an IMAGES table. 我有一个带有CAR表和IMAGES表的数据库。 I want to show all of the cars on the screen but only their first image as a thumbnail.
我想在屏幕上显示所有汽车,但只显示他们的第一张图片作为缩略图。 I'd be open to doing it in separate queries if needed, but I would like the CAR.IMAGES.SingleOrDefault() to hold the image record in the end so I'm not passing 10 images to my website and having to deal with the overhead.
如果需要,我会在单独的查询中做这件事,但我希望CAR.IMAGES.SingleOrDefault()最终保存图像记录,所以我没有将10张图像传递到我的网站并且不得不处理开销。
Thanks. 谢谢。
You can use some query like this: 你可以使用这样的一些查询:
var cars = from car in context.Cars
select {Name = car.Name, FirstImage = car.Images.FirstOrDefault()}
In this way you have just the first image in your car object, so it's as lightweight that you want. 通过这种方式,您只有汽车对象中的第一个图像,因此它就像您想要的那样轻量级。
你可以尝试直接的方法
var result = context.Cars.Select(_=> new {Car = _, Image = _.Images.FirstOrDefault()});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.