Adam
Adam

Reputation: 379

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.

Upvotes: 1

Views: 1048

Answers (2)

mehrandvd
mehrandvd

Reputation: 9116

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.

Upvotes: 1

Vladimir Furso
Vladimir Furso

Reputation: 338

You can try direct approach

var result = context.Cars.Select(_=> new {Car = _, Image = _.Images.FirstOrDefault()});

Upvotes: 1

Related Questions