Linq To Sql:成员日期没有支持的SQL转换

p.c*_*ell 4 c# linq linq-to-sql

考虑一个用于表示a的结果的类GroupBy().代码的目标是替换将按Created datetime字段分组并计算一堆行的存储过程.

public class Statistic
{
    public int NumRecords { get; set; }
    public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是引发异常/警告的代码:

//returning an IEnumerable<Statistic>
return db.MyTable
            .GroupBy(x => x.CreatedOn.Date ) //precision of date, not time.
            .Select(x => new Statistic(x.Key, x.Count()) ) //custom object
            .OrderBy(x => x.Date);
Run Code Online (Sandbox Code Playgroud)

例外:

成员Date没有受支持的SQL转换

当我重构代码加载到a时var,会生成异常/警告OrderBy().

问题:如何使用Linq To Sql避免此异常?

jru*_*ell 9

我在使用非默认构造函数之前遇到过这种情况.如果你使用对象初始化器,Linq to Sql可以找出映射:

return db.MyTable
            .GroupBy(x => x.CreatedOn.Date ) //precision of date, not time.
            .Select(x => new Statistic{Date = x.Key, NumRecords = x.Count()} ) //custom object
            .OrderBy(x => x.Date);
Run Code Online (Sandbox Code Playgroud)