.AsExpandable in Linq to Entity
Solution 1
Entity Framework's query processing pipeline cannot handle invocation expressions, which is why you need to call AsExpandable on the first object in the query. By calling AsExpandable, you activate LINQKit's expression visitor class which substitutes invocation expressions with simpler constructs that Entity Framework can understand.
— Josef Albahari
For more details I would recommend read from the author of LinqPad
Solution 2
There is no implicit conversion from a method group to an Expression (of a corresponding delegate type). There is an implicit conversion from a method group to a delegate of a matching signature. Therefore only the IEnumerable overload matches.
Of course, that's not to say that you need to use a lambda. Just write:
ctx.Set().AsExpandable().Where(ByName); Since you're passing in an expression (ByName is, after all, an Expression already, which is exactly what Queryable.Where requires) this will evaluate as a query, not in linq to objects.
Related videos on Youtube
Jitendra Gupta
Updated on September 14, 2022Comments
-
Jitendra Gupta over 1 year
In Linq to Entity, what does
.AsExpandable()
exactly do? Where and why to use it? Does it include all the related entities into query for lazy loading? -
carraua over 4 yearsIs this still relevant today in EF Core?
-
Bruno Santos over 4 yearsI am wondering as well if it's still necessary to call AsExpandable() when using EF Core, as it doesn't throw and it seems to work just fine.
-
Arad over 3 years@BrunoSantos Though it is true that it doesn't throw an exception in EF Core, but it would retrieve all the data from the data source and then attempt to execute the expression on client, which is inefficient. So, yes, you still need something like LinqKit.
-
Gerry almost 3 yearsSo what does AsExpandable do? If I was already an expert in Entity Framework I wouldn't be looking this up...
-
Ryan over 2 years@Gerry EF Query translation works by walking the query expression tree and looking up each method against a set of hardcoded SQL translations, which are mostly a subset of LINQ. As a result, EF has no idea what the LinqKit
.Invoke()
method actually means, and has no idea how to translate it. What.AsExpandable()
(and.Expand()
) does is walks the expression tree and swaps out any instances of.Invoke()
with the actual expression tree its invoking, before EF ever gets to it. In this way, EF only sees a "vanilla" expression tree with no.Invoke()
s.