Naor
Naor

Reputation: 24083

entity framework query using left join and if statement

I have two tables- workers and vehicles: Vehicle(Id, VehicleNumber) Workers(Id, Name, VehicleId)

I need to write a method that get a bool? parameter "isFree" and uses the entity framework (prefer lambda and not linq to entities) in order to:
if isFree==null then returns all vehicles
if isFree==true then returns all vehicles that doesn't belong to any worker
if isFree==false then returns all vehicles that belong to some worker

What is the best practise to solve this?

Upvotes: 0

Views: 1011

Answers (1)

Magnus
Magnus

Reputation: 46947

if(!isFree.HasValue)
  return context.Vehicles;
else if(isFree)
  return context.Vehicles.Where(v => !v.Workers.Any());
else
  return context.Vehicles.Where(v => v.Workers.Any());

Upvotes: 3

Related Questions