实体框架缓慢获取

时间:2015-03-14 01:20:05

标签: c# entity-framework entity-framework-6

我有一个大约有一百万条记录的数据库。我正在使用实体框架进行查询,并且日志记录告诉我实际执行时间是60ms。我不明白为什么,但完整的执行时间是3秒......(BeforeToList + AfterToList)。只提取了10行......

3秒很慢......

以下是代码:

    public IEnumerable<Event> GetEvents(IEnumerable<int> idList)
    {
        using (var db = new context())
        {
            db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
            var watch = Stopwatch.StartNew();
            var query = db.Event.Where(o => idList.Contains(o.EventId));
            var elapsedMs1 = watch.ElapsedMilliseconds;
            watch.Stop();
            watch.Reset();
            watch.Start();

            var query2 = query.ToList();
            watch.Stop();
            var elapsedMs2 = watch.ElapsedMilliseconds;

            Console.WriteLine("data.BeforeToList:" + elapsedMs1 + " --- AfterToList:" + elapsedMs2);
            return query2;
        }
    }

这是输出:

Test Name:  IsGetEventsReturn10Result
Test Outcome:   Passed
Result StandardOutput:  

data.BeforeToList:1148 --- AfterToList:2883


Debug Trace:
Opened connection at 2015-03-13 21:15:40 -04:00

SELECT 
    [Extent1].[EventId] AS [EventId], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[UrlReference] AS [UrlReference], 
    [Extent1].[Date] AS [Date], 
    [Extent1].[TimezoneId] AS [TimezoneId], 
    [Extent1].[Image1Id] AS [Image1Id], 
    [Extent1].[Image2Id] AS [Image2Id], 
    [Extent1].[CreatedBy] AS [CreatedBy], 
    [Extent1].[CreatedOn] AS [CreatedOn], 
    [Extent1].[UpdatedOn] AS [UpdatedOn], 
    [Extent1].[Status] AS [Status], 
    [Extent1].[SourceId] AS [SourceId], 
    [Extent1].[Source] AS [Source], 
    [Extent1].[CategoryID] AS [CategoryID], 
    [Extent1].[Price] AS [Price], 
    [Extent1].[Description] AS [Description], 
    [Extent1].[DescriptionUrl] AS [DescriptionUrl]
    FROM [dbo].[Event] AS [Extent1]
    WHERE [Extent1].[EventId] IN (366623, 366622, 366621, 366620, 366619, 366618, 366617, 366616, 366615, 366614)


-- Executing at 2015-03-13 21:15:41 -04:00

-- Completed in 60 ms with result: SqlDataReader



Closed connection at 2015-03-13 21:15:41 -04:00

1 个答案:

答案 0 :(得分:0)

在jlew的评论之后,我找到了一篇很好的文章来解释第一次调用(冷查询)和其他调用(热查询)之间的区别。

https://msdn.microsoft.com/en-ca/data/hh949853.aspx

为了帮助冷查询更快,我使用The Entity Framework Power Tools预先生成了视图。

无需更改代码。