I am facing serious performance issues... My query is supposed to filter Products with SQL directly in database. When I execute this code, it doesn't, and it returns all products and filters them in C#.
我正面临严重的性能问题……我的查询应该直接在数据库中使用SQL过滤产品。当我执行这段代码时,它没有,它返回所有产品并在c#中过滤它们。
MyContext context = new MyContext();
Func<Product, bool> query = (p => p.UPC.StartsWith("817"));
var products = context.Products.Where(query).Take(10);
I've noticed that the products variable is of type TakeIterator. When I change the code slightly, I get the filtering OK, but it forces me to put the query logic directly in the same method, which is what I want to avoid.
我注意到product变量是TakeIterator类型。当我稍微修改代码时,我得到了过滤,但是它迫使我将查询逻辑直接放在同一个方法中,这正是我想要避免的。
MyContext context = new MyContext();
var products = context.Products.Where(p => p.UPC.StartsWith("817")).Take(10);
This second version is of an undisclosed type by the Visual Studio debugger, but it shows as the query I am trying to end with, which is good!
第二个版本是由Visual Studio调试器提供的一种未公开的类型,但是它显示为我正在尝试使用的查询,这很好!
{SELECT TOP (10)
[Extent1].[Id] AS [Id],
[Extent1].[Brand] AS [Brand],
[Extent1].[Description] AS [Description],
[Extent1].[UPC] AS [UPC]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[UPC] LIKE N'817%'}
I need to figure out how to get a Func passed as an argument and execute the query in the same fashion as the first C# code excerpt, but with optimisations of the second.
我需要弄清楚如何让Func作为一个参数传递,并以与第一个c#代码片段相同的方式执行查询,但是要对第二个代码进行优化。
1 个解决方案
#1
1
Try this instead:
试试这个:
MyContext context = new MyContext();
Expression<Func<Product, bool>> query = (p => p.UPC.StartsWith("817"));
var products = context.Products.Where(query).Take(10);
And see this question for reference on why:
请参考这个问题:
Why would you use Expression<Func<T>> rather than Func<T>?
为什么要用
The accepted answer there is so complete that I don't dare try to explain it better!
公认的答案是如此完整,我不敢尝试更好地解释它!
#1
1
Try this instead:
试试这个:
MyContext context = new MyContext();
Expression<Func<Product, bool>> query = (p => p.UPC.StartsWith("817"));
var products = context.Products.Where(query).Take(10);
And see this question for reference on why:
请参考这个问题:
Why would you use Expression<Func<T>> rather than Func<T>?
为什么要用
The accepted answer there is so complete that I don't dare try to explain it better!
公认的答案是如此完整,我不敢尝试更好地解释它!