I have two very similar methods:
public IQueryable<User> Find(Func<User, bool> exp)
{
return db.Users.Where(exp);
}
public IQueryable<User> All()
{
return db.Users.Where(x => !x.deleted);
}
The top one, will not compile, saying it returns IEnumerable rather than IQueryable.
Why is this?
Also, I am aware I can add "AsQueryable()" on the end and it will work. What difference does that make though? Any performance hits? I understand that IQueryable has deferred execution and such, will I still get this benefit?
Enumerable.Where
takes Func<T, bool>
.
Queryable.Where
takes Expression<Func<T, bool>>
.
You're calling Where with a Func<T, bool>
, therefore only the Enumerable.Where
call is applicable, and that returns IEnumerable<T>
.
Change your method to:
public IQueryable<User> Find(Expression<Func<User, bool>> exp)
{
return db.Users.Where(exp);
}
and it should be okay. Basically you want to pass in an expression tree instead of a delegate, so that the expression can be converted to SQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With