【问题标题】:how to use sql function in linq如何在linq中使用sql函数
【发布时间】:2016-11-23 15:18:45
【问题描述】:

我想将此过程更改为实体框架的 linq:

SELECT COUNT([dbo].[Events].[Request]) as requestCount, 
MONTH([dbo].[Events].[Request]) as months
FROM [dbo].[Events]
GROUP BY MONTH([dbo].[Events].[Request])

我使用了许多解决方案,但没有一个有效! 提前致谢!

编辑:我使用它们的解决方案: 解决方案1: The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

但我从来没有找到 SqlFunctions!!

解决方案2:

var events = db.Events.GroupBy(x => Convert.ToDateTime(x.Request).Month)
                      .Select(g => new { max = g.Max(), Count = g.Count() })
                      .ToList();

给我这个错误:

LINQ to Entities 无法识别方法“System.DateTime” ToDateTime(System.DateTime)' 方法,并且该方法不能 翻译成商店表达式。

【问题讨论】:

  • MONTH不需要sql函数,可以使用DateTimeMonth属性。顺便说一句,您忽略了此查询中的年份。
  • 我使用了许多解决方案,但没有一个有效! - 在问题中添加一个,以便我们帮助您解决它
  • 好的,我编辑了我的问题!

标签: c# sql sql-server entity-framework linq


【解决方案1】:
var events = db.Events.GroupBy(x => x.Request.Month)
                      .Select(g => new { Month = g.Key, RequestCount = g.Count() })
                      .ToList();

如果 Request 不是 DateTime 就像您的示例可能推断的那样,那么您可以:

var events = db.Events.Select(item => new 
                            { 
                                Month = DateTime.Parse(item.Request).Month,             
                                Event = item
                            })
                      .GroupBy(x => x.Month)
                      .Select(g => new { Month = g.Key, RequestCount = g.Count() })
                      .ToList();

为了好玩,您可以使用 GroupBy 的不同重载(其中 select lambda 是另一个参数:

var events = Events
    .Select(item => new
        {
            Month = DateTime.Parse(item.Request).Month,
            Event = item
        })
    .GroupBy(x => x.Month, 
        (key, collection) => new 
        { 
            Month = key, 
            RequestCount = collection.Count() 
        }).ToList();

【讨论】:

  • @amirstack - 添加了另一种方法:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 2011-08-24
  • 2021-12-11
相关资源
最近更新 更多