简体   繁体   English

实体框架5和SQL查询

[英]Entity Framework 5 and SQL Queries

I am facing serious performance issues... My query is supposed to filter Products with SQL directly in database. 我面临严重的性能问题...我的查询应该直接在数据库中过滤带有SQL的产品。 When I execute this code, it doesn't, and it returns all products and filters them in C#. 当我执行此代码时,它没有,它返回所有产品并在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. 我注意到products变量是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. 当我稍微更改代码时,我得到了过滤确定,但它迫使我将查询逻辑直接放在同一个方法中,这是我想要避免的。

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#代码摘录相同的方式执行查询,但优化第二个。

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>? 为什么要使用Expression <Func <T >>而不是Func <T>?

The accepted answer there is so complete that I don't dare try to explain it better! 接受的答案是如此完整,以至于我不敢尝试更好地解释它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM