I have a complex LINQ to Entities query that the where is getting too long. I want to split it up into some well named methods so others can understand it. This post seems to imply that I can do that as long as I'm returning an Expression EF can translate. https://stackoverflow.com/a/18338476/4812782
Here is my simplified code. I cannot retrieve the data before filtering because it will be over 100,000 records. My database is Oracle.
var q = _context.vehicles
.Where(x => IsActiveVehicle())
.ToList()
Expression<Func<tb_vehicle, bool>> IsActiveVehicle()
{
return vehicle => vehicle.type == "R" &&
vehicle.status != "E" &&
vehicle.deleted == false;
}
I get the error
Cannot implicity convert type 'System.Linq.Expressions.Expression>' to 'bool'. Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
Any help is appreciated.
This is incorrect, as noted by the error:
.Where(x => IsActiveVehicle())
That is creating a new expression that contains your expression.
You want to actually pass the Expression<Func<>>
to the .Where
.
var q = _context.vehicles
.Where(IsActiveVehicle())
.ToList()
Pay attention to the question/answer you linked and you'll see it.
Another way to look at it:
.Where(x => IsActiveVehicle())
Means the following non-sense:
.Where(x => ((vehicle) => vehicle.type == "R" &&
vehicle.status != "E" &&
vehicle.deleted == false))
However, this:
.Where(IsActiveVehicle())
Means the following, which makes more sense:
.Where(vehicle => vehicle.type == "R" &&
vehicle.status != "E" &&
vehicle.deleted == false)