【问题标题】:Only parameterless constructors and initializers are supported in LINQ to EntitiesLINQ to Entities 中仅支持无参数构造函数和初始化程序
【发布时间】:2014-07-17 19:10:27
【问题描述】:

我得到这个错误,

 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 仅支持无参数构造函数和初始化程序。

【问题讨论】:

    标签: c# .net linq


    【解决方案1】:

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

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

    否则,您必须使用 AsEnumerable 切换到 Linq-to-Objects 上下文,然后创建新的 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();
    

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多