Query execution time in Entity Framework vs. SQL Server

I have a query written in Linq To Entities:

db.Table()
    .Where(x => x.Date >= dateStart)
    .Where(x => x.Date  new
    {
        x.EntityId,
        x.EntityName,
        x.EntityToken
    })
    .Select(x => new EntityBrief
    {
        EntityId = x.Key.EntityId,
        EntityName = x.Key.EntityName,
        EntityToken = x.Key.EntityToken,
        Quantity = x.Count()
    })
    .OrderByDescending(x => x.Quantity)
    .Take(5)
    .ToList();

The problem is that it takes 4 seconds when executing in the application using EF. But when I take the created pure SQL Query from that query object (using Log) and fire it directly on SQL Server, then it takes 0 seconds. Is it a known problem?

Firstly, try improving your query:

var entityBriefs =
  Table().Where(x => x.Date >= dateStart && x.Date  x.EntityId)
                    .OrderByDescending(x => x.Count())
                    .Take(5)
                    .Select(x => new EntityBrief
                    {
                        EntityId = x.Key.EntityId,
                        Quantity = x.Count()
                    });

var c = entityBriefs.ToDictionary(e => e.EntityId, e => e);

var entityInfo = Table().Where(o => mapping.Keys.Contains(o.EntityId).ToList();

foreach(var entity in entityInfo)
{
   mapping[entity.EntityId].EntityName = entity.EntityName;
   mapping[entity.EntityId].EntityToken = entity.EntityToken;
}

You may also compile queries with the help of CompiledQuery.Compile
, and use it further with improved performance.

http://msdn.microsoft.com/en-us/library/bb399335%28v=vs.110%29.aspx

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Query execution time in Entity Framework vs. SQL Server

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录