实体框架正在执行太多查询

时间:2013-04-23 15:04:13

标签: c# sql-server asp.net-mvc performance entity-framework

我需要找到特定用户的不同广告系列。用户拥有CodeRights,CodeRights包含包含Campaign的代码和代码。这是CodeRight类

public class SmartCodeRight
{
        [Key, Column(Order = 1)]
        public long UserId { get; set; }
        public virtual User User { get; set; }

        [Key, Column(Order = 2)]
        public long CodeId { get; set; }
        public virtual SmartCode Code { get; set; }

        public CodeRight CodeRight { get; set; }
}

我会为此编写以下SQL:

SELECT * 
FROM campaigns 
WHERE campaignid IN (SELECT DISTINCT campaignid  
                     FROM smartcodes t1 
                     INNER JOIN smartcoderights t2 ON t1.codeId = t2.codeId
                     WHERE t2.userid = @userId)

使用EF我正在编写此代码:

var v = user.CodeRights.Select(r => r.Code.Campaign).Distinct().ToList();

现在进行性能分析我发现EF正在为每个存在的CodeRight执行2个SQL查询。

我还计算了整个执行的时间,而 EF在使用ADO.Net时需要大约400毫秒,它只有~8

现在我的问题是,如果EF真的很慢或者我做错了什么?

编辑

正在为每个CodeRight执行以下两个块

exec sp_executesql N'SELECT 
[Extent1].[CodeId] AS [CodeId], 
[Extent1].[CodeTitle] AS [CodeTitle], 
[Extent1].[CodeContent] AS [CodeContent], 
[Extent1].[CreatedOn] AS [CreatedOn], 
[Extent1].[IsActive] AS [IsActive], 
[Extent1].[Deleted] AS [Deleted], 
[Extent1].[OwnerId] AS [OwnerId], 
[Extent1].[Tags] AS [Tags], 
[Extent1].[CampaignId] AS [CampaignId]
FROM [dbo].[SmartCodes] AS [Extent1]
WHERE [Extent1].[CodeId] = @EntityKeyValue1',N'@EntityKeyValue1 bigint',@EntityKeyValue1=24
go

exec sp_executesql N'SELECT 
[Extent1].[CampaignId] AS [CampaignId], 
[Extent1].[Name] AS [Name], 
[Extent1].[Description] AS [Description], 
[Extent1].[AdminId] AS [AdminId]
FROM [dbo].[Campaigns] AS [Extent1]
WHERE [Extent1].[CampaignId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=12
go

1 个答案:

答案 0 :(得分:10)

你应该花时间看Fetch Plans for Entity Framework。要让EF执行加入,您必须使用Include关键字。

当您获得user对象时,它必须是您初始查询的一部分:

var user = context.Users
    .Include("CodeRights.Code")
    .Include("CodeRights.Campaign")
    .FirstOrD‌​efault(u => u.Id == id);