【问题标题】:LINQ - grouping by date causes NotSupportedException [duplicate]LINQ - 按日期分组导致 NotSupportedException [重复]
【发布时间】:2017-06-03 09:04:05
【问题描述】:

我正在尝试在 MVC 视图中显示一组到服务的连接数。

我遇到的问题是,当我尝试检查出于分页目的返回了多少项目时,我得到了 System.NotSupportedException

LINQ to Entities 不支持指定的类型成员“日期”。仅支持初始化器、实体成员和实体导航属性。

这是我的 IQueryable 方法

private IQueryable<ConnectionItem> ListItems(DataContext dataContext)
{
    return
        from conn in dataContext.Connections
        join cfg in dataContext.Configurations on conn.ConfigID equals cfg.ConfigID
        join u in dataContext.Users on cfg.UserID equals u.UserID
        where conn.Successful && u.AccountEventID == 123
        group 1 by conn.CreatedDate.Date into g
        select new ConnectionItem
        {
            CreatedDate = g.Key,
            NumberOfConnections = g.Count(),
        };
}

这里是连接项

public class ConnectionItem
{
    public DateTime CreatedDate { get; set; }
    public int NumberOfConnections { get; set; }
}

我这样称呼它:

var items = ListItems(dataContext);
var total = items.Count() // this causes the exception

我的最终结果应该是日期的集合,例如 2017-01-10 和当天建立的连接数。

【问题讨论】:

标签: c# entity-framework linq


【解决方案1】:

如果您想要截断时间,请使用DbFunctions.TruncateTime 方法:

//...
group 1 by DbFunctions.TruncacteTime(conn.CreatedDate) into g
//...

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多