【问题标题】:Convert Sql query containing Group By, Distinct and Aggregate function to Linq to Entity将包含 Group By、Distinct 和 Aggregate 函数的 Sql 查询转换为 Linq to Entity
【发布时间】:2016-04-21 10:46:37
【问题描述】:

我是 Linq to Entity 的新手。我尝试了将简单的 sql 查询放入 Linq to Entity 的方法。
这是我的查询。

select distinct top 5 convert(varchar,CreatedDate,111) as date, count(Id)
FROM  
XYZ l 
GROUP BY convert(varchar,CreatedDate,111) order by date desc

我试过了:

IQueryable<XYZ> dalMemberList = dbContext.XYZ.Where(c => c.IsDeleted == false).GroupBy(g => g.CreatedDate).OrderByDescending(o => o.CreatedDate);

但这对我不起作用。 谁能帮我把这个简单的查询转换成 Linq to Entity。

【问题讨论】:

  • 您能否详细说明“不适合我” - 您是否收到错误消息?如果是这样,错误是什么?您是否得到与预期不同的结果?如果是这样,您的输入数据是什么,您得到的结果是什么,您期望的结果是什么?
  • .OrderByDescending之前插入.Select(g =&gt; new { CreatedDate = g.Key, Count = g.Count() })
  • 对于它的价值,在您的查询中DISTINCT 是多余的,因为您也有分组依据。你不应该convert to varchar without a length,而且似乎根本没有必要转换为varchar,为什么不直接做CONVERT(DATE, CreatedDate)
  • @GarethD :它给了我错误,'System.Linq.IGrouping 不包含'CreateDate'的定义'
  • 好吧,兄弟,如果你不告诉我们究竟是什么不适合你,我看不出我们能提供什么帮助。

标签: sql linq linq-to-sql linq-to-entities


【解决方案1】:

在 GroupBy 之后,您必须将结果投影到新对象。然后你可以对那个新对象进行 OrderBy。

var dalMemberList = dbContext.XYZ.
Where(c => c.IsDeleted == false)
.Select(converted => new {
NewDate = converted.CreatedDate.Date.ToShortDateString(), //or other convertions
converted.IsDeleted,
converted.CreatedDate
} )
.GroupBy(g => g.NewDate)
.Select(b=> new  {
key = b.Key,
list = b.OrderByDescending(t=>t.CreatedDate).Take(5)
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2012-10-26
    • 1970-01-01
    • 2011-11-15
    相关资源
    最近更新 更多