Greeed
Greeed

Reputation: 419

EF6 query building to get the first object in the list

I have a Car class:

public class Car
    {
      public int Id { get; set; }
      public List<Engine> Engine { get; set; } 
    }

public class Engine
    {
      public int Id { get; set; }
      public string EngineName{ get; set; } 
    }

And I want to create a select query which would look like this:

 IQueryable<Car> querybuilder = carDbSet.Include(x=>x.Engine);   // simple example

//this works

if(sunIsShining)
{
    querybuilder = querybuilder.Where(e =>e.Id == 5)   // all records where carId = 5
}

//this doesn't work

  if(windIscold)
  {
      querybuilder = querybuilder.Where(e =>e.Engine.FirsOrDefault().EngineName == "V8" )

   // e =>e.Engine.FirsOrDefault().EngineName value is null when in the db I have V8..
  }

I need to validate only on the first record of an engine despite the fact that relationship is 1 car to many engines.. how do I do this? should I somehow create a subSelect which would return only the first engine record?

Upvotes: 1

Views: 199

Answers (1)

Steve Lillis
Steve Lillis

Reputation: 3256

You can use Any if it doesn't matter which record is V8 for the car's engines:

 querybuilder = querybuilder.Where(e => e.Engine.Any(a => a.EngineName == "V8"));

If you definitely need to be the first row only, it'll get significantly more complicated.

Upvotes: 2

Related Questions