使用是否传递给方法减缓实体框架查询lambda表达式? [英] Does using a lambda expression passed into a method slow down an Entity Framework query?

查看:103
本文介绍了使用是否传递给方法减缓实体框架查询lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法:

public static void GetObjects()
{
    using(MyContext context = new MyContext())
    {
         var objects = context.Bars.Where(b => b.Prop1 != null)
                       .Select(b => new MyObject{Prop = b.Prop1, Name = b.Name})
                       .ToList();
         foreach(var object in objects)
         {
             // do something with the object
         }
    }
}

我重构,以使其更加通用,这样我可以在函数功能这样我可以指定其中,语句和表被分配到酒吧是什么性质> MyObject.Prop 是这样的:

I refactored the method to make it more general so that I can pass in a Func so that I can specify the where statement and what property from the Bars table gets assigned to MyObject.Prop like this:

public static void GetObjectsV2(Func<Bar, bool> whereFunc, Func<Bar, string> selectPropFunc)
{
    using(MyContext context = new MyContext())
    {
         var objects = context.Bars.Where(whereFunc)
                       .Select(b => new MyObject{Prop = selectPropFunc(b), Name = b.Name})
                       .ToList();
         foreach(var object in objects)
         {
             // do something with the object
         }
    }
}

GetObjectsV2 似乎跑得比 GetObjects 。有没有这会影响性能的原因,如果是这样,是否有关于这一点的同时任何方面仍保持功能灵活?

GetObjectsV2 seems to run much slower than GetObjects. Are there any reasons this would affect performance, and if so, are there any ways around this while still keeping the function flexible?

推荐答案

在运行速度较慢的原因是因为你传递一个 Func键<酒吧,布尔> 这迫使以检索所有的酒吧,然后运行Func键上返回的结果上下文组。使这个运行得更好的方法是在传递表达式来; Func键<酒吧,布尔>>

The reason it is running slower is because you are passing in a Func<Bar, bool> 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<Func<Bar, bool>>

推杆所有一起将导致以下内容:

Putting that all together will result in the following:

public static void GetObjectsV2(Expression<Func<Bar, bool>> whereFunc, Expression<Func<Bar, string>> 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
         }
    }
}

这篇关于使用是否传递给方法减缓实体框架查询lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆