【问题标题】:DateTime.ToString("MM/dd/yyyy") inside linq threw an error [duplicate]linq 中的 DateTime.ToString("MM/dd/yyyy") 引发错误 [重复]
【发布时间】:2018-06-09 01:05:43
【问题描述】:

DateTime.ToString("MM/dd/yyyy") 里面 linq 抛出一个错误。这是我的代码:

public IEnumerable<EmployeeViewModel> GetAllEmployees()
{
    List<EmployeeViewModel> vm = (
        from a in db.Employees
        select new EmployeeViewModel
        {
            EmployeeId = a.EmployeeId,
            EmployeeName = a.EmployeeName,
            HiredDateString = a.HiredDateTime.ToString("MM/dd/yyyy"),
            HiredTimeString = a.HiredDateTime.ToString("h:mm tt"),
            Description= a.Description
            }).ToList();
    return vm;
}

编辑:HiredDateString 和 HiredTimeString 是 ViewModel 中的字符串。

为此我收到以下错误:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
</ExceptionMessage>
<ExceptionType>System.NotSupportedException</ExceptionType>

如果我简单地使用:a.HiredDateTime.ToString(),它不会抛出错误。但它给了我完整的 DateTime 字符串;我想分别获取日期和时间字符串。 非常感谢您的帮助。

【问题讨论】:

  • a.HiredDateTimeDateTime 还是 string?看起来可能是string
  • 为什么要将日期存储为字符串?这总是坏主意。如果您想以某种方式显示它们,请在视图层中进行
  • @BobKaufman 这是一个字符串

标签: c# entity-framework linq


【解决方案1】:

你不能在 linq 表达式中使用日期时间格式。你应该这样做:

HiredDateString = a.HiredDateTime,

你应该在显示时格式化这些数据。

例如在剃须刀页面中:

foreach (var item in vm )
            {
                @item.HiredDateString.ToString("MM/dd/yyyy")
            }

【讨论】:

  • 我找到了解决方案:我只是错过了 .ToList() 或 .AsEnumerable() 就像我做 db.Employees.AsEnumerable() 一样,它按预期工作。
  • 一些 Rando 刚刚将我的问题标记为重复。但绝不是重复的。也投了反对票。这些所谓的“专家”从不让新人做好事。显然,在内心深处,他们想扼杀新来者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多