简体   繁体   中英

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.

I have a database with a CAR table and an IMAGES table. 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.

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()});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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