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

后端 未结 2 1346
暗喜
暗喜 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:27

    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
             }
        }
    }
    

提交回复
热议问题