.AsExpandable in Linq to Entity

19,321

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.

Share:
19,321

Related videos on Youtube

Jitendra Gupta
Author by

Jitendra Gupta

Updated on September 14, 2022

Comments

  • Jitendra Gupta
    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?

    • D Stanley
      D Stanley almost 9 years
      AsExpandable is not a built-in Ling funciotn. If you're talking about the extension method from LinqKit then read the documenation thare as well as the blog on which is was based.
  • carraua
    carraua over 4 years
    Is this still relevant today in EF Core?
  • Bruno Santos
    Bruno Santos over 4 years
    I 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
    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
    Gerry almost 3 years
    So what does AsExpandable do? If I was already an expert in Entity Framework I wouldn't be looking this up...
  • Ryan
    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.