Does using a lambda expression passed into a method slow down an Entity Framework query?

后端 未结 2 1344
暗喜
暗喜 2021-02-15 00:55

I have a method:

public static void GetObjects()
{
    using(MyContext context = new MyContext())
    {
         var objects = context.Bars.Where(b => b.Prop1         


        
2条回答
  •  走了就别回头了
    2021-02-15 01:34

    As I discovered in my own question, .Where(o => whereFunc(o)) is not the same as .Where(whereFunc) in the Entity Framework.

    The first one, .Where(Expression>) works like any other linq call, simply appending the expression to the expression tree.

    In the second case, .Where(Func>), it will compile and evaluate the linq call (which so far is just context.Bars) before applying the whereFunc predicate.


    So, to answer your question, the second one is much slower because it is pulling the entire Bars table into memory before doing anything with it. Using .Where(o => whereFunc(o)) instead should fix that

    (or, as Mark suggests, change the type of whereFunc to Expression>, which Func is implicitly convertible to)

提交回复
热议问题