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

时间:2009-09-09 16:53:37

标签: c# linq linq-to-sql

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

public class Statistic
{
    public int NumRecords { get; set; }
    public DateTime Date { get; set; }
}

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

//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);

例外:

  

成员日期不受支持   转换为SQL

当我重构代码以加载到var时,会在OrderBy()上生成异常/警告。

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

2 个答案:

答案 0 :(得分:8)

我在使用非默认构造函数之前遇到过这种情况。如果您使用object initializer代替,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);

答案 1 :(得分:1)

事实证明,当我预期时,查询没有被执行并加载到变量中。

以下内容将按预期进行评估和运行。

IEnumerable<Statistic> stats = db.MyTable           
        .GroupBy(x => x.CreatedOn.Date )
        .Select(x=> new Statistic(x.Key, x.Count()) );


    return stats.OrderBy(x=>x.Date);