LINQ to Entities中只支持无参数构造函数和初始化函数

本文关键字:构造函数 参数 初始化 函数 支持 to Entities LINQ | 更新日期: 2023-09-27 18:05:39

我得到这个错误,

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

当我试图从自定义类型投影到日期时间数组时,请注意DateCreatedDateTime类型。

你知道怎么解决吗?

           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只支持无参数构造函数和初始化式

LINQ to Entities中只支持无参数构造函数和初始化函数

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

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

否则你必须使用AsEnumerable切换到对象链接上下文,然后创建新的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();