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

后端 未结 2 922
南方客
南方客 2021-02-15 00:56

I have a method:

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


        
2条回答
  •  梦毁少年i
    2021-02-15 01:11

    The reason it is running slower is because you are passing in a Func which forces the context to retrive ALL Bars and then run the Func on the returned result set. A way to make this run better is to pass in Expression>

    Putting that all together will result in the following:

    public static void GetObjectsV2(Expression> whereFunc, Expression> selectPropFunc)
    {
        using(MyContext context = new MyContext())
        {
             var objects = context.Bars.Where(whereFunc)
                           .Select(selectPropFunc)
                           .ToList();
             foreach(var object in objects)
             {
                 // do something with the object
             }
        }
    }
    

提交回复
热议问题