我有一个从我的数据库中提取的错误集合。时间存储为 UTC,但我想将其转换为 CST:

var errors = _errorsRepository.Errors.
    Select(e => new ErrorViewModel
    {
        ErrorId = e.ErrorId,
        Application = e.Application,
        Host = e.Host,
        Type = e.Type,
        Source = e.Source,
        Message = e.Message,
        User = e.User,
        StatusCode = e.StatusCode,
        TimeUtc = TimeZoneInfo.ConvertTimeFromUtc(
            e.TimeUtc, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")),
        Sequence = e.Sequence,
        AllXml = e.AllXml
     });

但我收到此错误:



有谁知道我能做些什么来解决这个问题?

最佳答案

LINQ to Entities 会尝试将您的 LINQ 查询转换为 SQL 查询。由于您编写的部分内容无法转换为 SQL,因此您会收到此错误。

您可以通过首先使用 ToList() 将查询转换为内存中的对象,然后使用 LINQ to Objects 来获得所需的结果来解决此问题:

var errors = _errorsRepository.Errors.ToList().
Select(e => new ErrorViewModel
{
    ErrorId = e.ErrorId,
    Application = e.Application,
    Host = e.Host,
    Type = e.Type,
    Source = e.Source,
    Message = e.Message,
    User = e.User,
    StatusCode = e.StatusCode,
    TimeUtc = TimeZoneInfo.ConvertTimeFromUtc(
        e.TimeUtc, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")),
    Sequence = e.Sequence,
    AllXml = e.AllXml
 });

请注意,这将首先将 _errorsRepository 中的所有错误放入内存中。在这种情况下,看起来这对您来说并不重要,因为无论如何您都会获得所有这些。

关于c# - LINQ to Entities 无法识别方法 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' 方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15735022/

10-12 00:13
查看更多