简体   繁体   中英

EF4.1 eager loading query

I am using EF to implement a search function to search cars on a website. It's working fine, but I would like to optimise performance. Cars have a make and model, and a number of images. It's easy enough to include the make and model using .Include(), but I am having trouble with the images... at the moment, the main query is being executed, and then EF queries the db for each search result to get the images. I'd like to include this all in the one query. I can use .Include(), but that obviously loads all images, and I actually only want one (any) image. Is there a way of doing this?

Thanks heaps!

You have to use separate query for images. For example:

context.Configuration.LazyLoadingEnabled = false;
var cars = context.Cars.Include(c => c.Model).Where(c => c.Type == "abc").ToList();
var images = context.Images.Where(i => i.Car.Type == "abc" && ...).ToList();

Now if you have everything correctly setup EF should fix relationship between cars and images and each car should have its navigation property for images filled with just images loaded by the second query.

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