LINQ to Entities中仅支持无参数构造函数和初始值设定项

时间:2014-05-28 13:56:58

标签: c# .net linq

我收到此错误,

 Only parameterless constructors and initializers are supported in LINQ to Entities.

当我尝试从自定义类型投影到DateTime数组时,请注意DateCreated类型为DateTime

知道怎么解决吗?

           DateTime[] data = analyticRepo.GetAll()
                                      .Where(x => DbFunctions.TruncateTime(x.DateCreated) == report.DateCreated.Date)
                                      .Select(x => new DateTime(
                                          x.DateCreated.Year,
                                          x.DateCreated.Month,
                                          x.DateCreated.Day,
                                          x.DateCreated.Hour,
                                          x.DateCreated.Minute,
                                          x.DateCreated.Second,
                                          x.DateCreated.Millisecond))
                                      .ToArray();

LINQ to Entities中仅支持无参数构造函数和初始值设定项。

1 个答案:

答案 0 :(得分:5)

如果x.DateCreated已经是DateTime,只需选择

DateTime[] data = analyticRepo.GetAll()
                              .Where(x => DbFunctions.TruncateTime(x.DateCreated) == report.DateCreated.Date)
                              .Select(x => x.DateCreated)
                              .ToArray();

否则,您必须实现所有结果,然后创建新的DateTime个对象:

DateTime[] data = analyticRepo.GetAll()
                              .Where(x => DbFunctions.TruncateTime(x.DateCreated) == report.DateCreated.Date)
                              .Select(x => x.DateCreated)
                              .AsEnumerable() // transition to Linq-to-Objects
                              .Select(x => new DateTime(
                                  x.Year,
                                  x.Month,
                                  x.Day,
                                  x.Hour,
                                  x.Minute,
                                  x.Second,
                                  x.Millisecond))
                              .ToArray();