【发布时间】:2014-01-16 20:14:00
【问题描述】:
我在尝试编写查询时遇到问题。我有一张表,里面有大约 6000 条记录。
目前在我的开发机器上运行大约需要 15 秒。一台运行 vs2012 和 sql2012 的 32gb ram 四核 win8 机器。所以它不是我的机器而是我的错误代码。
public IEnumerable<Customer> GetByStoreIdAndContainingName(Guid storeId, string containing)
{
using (var context = new Entities())
{
var store = context.Stores.FirstOrDefault(b => b.StoreId == storeId);
if (store == null) return null;
var business = store.Business;
var consumers = new List<Consumer>();
consumers =
business.ConsumerIdentities.Select(ci => ci.Consumer)
.Distinct()
.Where(x => x.FirstName.ToLower().Contains(containing.ToLower()))
.ToList();
数据库表的布局是
商业
企业ID
名称
等等
StoreId
商店ID
店名
业务编号
消费者
消费者ID
名字
姓氏
消费者身份
企业ID
消费者身份类型
消费者身份价值
谁能看到我做错了什么明显的事情,需要很长时间才能返回查询结果?
开启 SQL Profiler 很可怕。第一个查询是从 ConsumerIdentity 表中选择与企业 ID 匹配的所有内容。太棒了,然后得到商务表。
然后似乎对每条记录都进行了调用,例如
exec sp_executesql N'SELECT
[Extent1].[ConsumerId] AS [ConsumerId],
[Extent1].[UserID] AS [UserID],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[IsMale] AS [IsMale],
[Extent1].[DateOfBirth] AS [DateOfBirth],
FROM [dbo].[Consumer] AS [Extent1]
WHERE [Extent1].[ConsumerId] = @EntityKeyValue1',N'@EntityKeyValue1 uniqueidentifier',@EntityKeyValue1='952ED7B8-2123-49E2-BAE3-69FBD713BACB'
所以看起来我的 where 语句没有被应用
【问题讨论】:
-
我将首先查看实际的 sql 查询及其在 microsoft sql server management studio 中的执行计划(您可以使用 sql profiler 跟踪查询)。
-
如果还没有,请尝试在 Release(没有任何调试标志)配置中运行
-
或使用此调试可视化工具:visualstudiogallery.msdn.microsoft.com/…
-
你在这些表上有什么索引?
-
目前我的表上没有任何索引。我现在会尝试添加这些
标签: c# linq entity-framework linq-to-entities