1

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.

1
  • Seems like you want Where(IsActiveVehicle()) Commented Oct 25, 2019 at 15:22

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I completely missed that! Thank you!! I'm probably going to have around 10 custom methods like this. Is there anyway to link them together in one where clause or will I need a new where clause for each?
Such as .Where(IsActiveVehicle && IsNotDocked())
Assuming you plan on chaining them with an AND, the best way is to make multiple calls to .Where().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.