c# - Linq 查询耗时过长

标签 c# linq entity-framework

我想知道是否有人可以帮助我解决这个问题。我有一个 LINQ 查询 - 没有问题,但返回数据的时间太长了

var result = Context.paf_wgs84.Where(c => c.Postcode.Contains(postcode)).Take(15);

非常简单,用户输入时的想法,使用 AJAX,返回一组 15 个可能的匹配项。

问题是,有160万条记录

在 Management Studio 中运行以下代码大约需要 3 秒

SELECT   code
FROM     paf_wgs84
WHERE    (code LIKE '%EC1%')

因为运行下面的代码不到一秒

SELECT   TOP 15  code
FROM     paf_wgs84
WHERE    (code LIKE '%EC1%')

有没有一种方法可以在不使用 .take() 的情况下在 LINQ 中做类似的事情?

最佳答案

你可以尝试这样的事情。这只会返回一列。

var result = Context.paf_wgs84.Where(c => c.Postcode.Contains(postcode)).Select(x=>new {x.Postcode}).Take(15);

生成的 Sql 语句如下所示。

/*
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%s%'
-- EndRegion
SELECT TOP (15) [t0].[code]
FROM [paf_wgs84] AS [t0]
WHERE [t0].[code] LIKE @p0
*/

关于c# - Linq 查询耗时过长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7188653/

相关文章:

c# - PFX 文件导入到 C# 中的 Webhosting 存储

linq - 为 linq groupby 编写自定义比较器

c# - 无法将类型 'Task<System.Collections.Generic.IEnumerable<IClass>>' 隐式转换为 'System.Collections.Generic.IEnumerable<IClass>

c# - Linq 查询 nhibernate;不支持异常

c# - Queryable.Any() 返回 null?

php - Symfony2/学说 : how to add more of the same entity in the same collection?

C#MQ Api如何在空队列的情况下获取消息而不会出现异常

c# - 使用MVVM按下按钮时如何调用异步方法?

sql-server - Entity Framework 代码优先迁移,sql用户权限?

c# - 为什么 libphonenumber 网站返回的结果与 libphonenumber 库不同?