Twenty
Twenty

Reputation: 5961

Get entity with all its child which meet a certain condition

Just a disclaimer, this might have been already asked, but I didn't really knew what to search for.

So basically I have the following model:

public class Car
{
    public int Id { get; set; }

    public string UniqueName { get; set; }

    public List<Feature> Features { get; set; }
}

public class Feature
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }
}

Lets say I want to get a car which's UniqueName equals Bentle, but only with Features which cost less then 100$.

I could do something like this:

var car = DbContext.Cars.FirstOrDefault(x=> x.UniqueName == "Bentle");
car.Features = car.Features.Where(x=> x.Price <= 100).ToList();

This indeed works, but it seems to me as a lot of unnecessary conversions. Is there any way to shorten this Query?

A few Requirements:

Upvotes: 1

Views: 51

Answers (1)

Abdullah Dibas
Abdullah Dibas

Reputation: 1507

Although I don't see any unnecessary conversion in your query, but you can try the following if you want to execute your request in one line:

var car = DbContext.Cars.Where(x=> x.UniqueName == "Bentle").Select(car =>
          new Car()
          { 
            Features = car.Features.Where(x=> x.Price <= 100),
            .
            .
            /*here copy the remaining properties of car object*/
          }).FirstOrDefault();

Upvotes: 1

Related Questions