如何获得从OrderBy / GroupBy生成的新表的主要内容?

时间:2014-10-02 10:15:27

标签: c# linq entity-framework visual-studio

如何从OrderBy / GroupBy生成新表的主要内容?

var something = (from m in _db.Requests
                 where m.StoreID == myRequest.StoreID
                 where m.AcceptedTime != null
                 where System.Data.Entity.DbFunctions.TruncateTime(m.RequestTime) == today
                 group m by m.StaffID into g
                 let TotalPoints = g.Count()
                 orderby TotalPoints ascending
                 select new { User = g.Key});

然后,我试着得到第一个结果,这将是最少的次数" m"出现在我的Requests

var thisStaff = something.Select(o=>o.User).Take(1).ToString();

然而," thisStaff"的价值不是StaffID,它是我Request表的关键字。其中的值是

SELECT TOP (1) [Project1].[StaffID] AS [StaffID]
FROM ( SELECT [GroupBy1].[A1] AS [C1], [GroupBy1].[K1] AS [StaffID]
       FROM   ( SELECT [Extent1].[StaffID] AS [K1], COUNT(1) AS [A1]
                FROM   [dbo].[Requests] AS [Extent1]
                WHERE  ([Extent1].[StoreID] = @p__linq__0) AND
                       ([Extent1].[AcceptedTime] IS NOT NULL) AND
                       ((convert (datetime2, convert(varchar(255), [Extent1].[RequestTime], 102) , 102)) =  @p__linq__1)
                GROUP BY [Extent1].[StaffID] ) AS [GroupBy1] ) AS [Project1]
ORDER BY [Project1].[C1] ASC

请建议我应该如何改变它。顺便说一句,我也试过使用以下内容并得到几乎相同的结果。

var something2 = _db.Requests
    .Where(o => o.StoreID == myRequest.StoreID)
    .Where(o => o.AcceptedTime != null)
    .Where(o => System.Data.Entity.DbFunctions.TruncateTime(o.RequestTime) == today)
    .GroupBy(x => x.StaffID)
    .Select(x => new
    {
        Count = x.Count(),
        Name = x.Key,
    })
    .OrderBy(x => x.Count)
    .Take(1);

1 个答案:

答案 0 :(得分:0)

您的查询没问题,您只是缺少调用数据库并返回结果的方法调用(EF的一项功能是延迟执行),FirstOrDefault()应该可以解决问题:

var thisStaff = something.Select(o => o.User).FirstOrDefault();

您看到的值是您构造的IQueryable为其ToString方法返回的值(它将是执行查询时针对数据库运行的SQL)。