我有一个从数据库中提取的错误集合。时间存储为 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 does not recognize the method 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' method, and this method cannot be translated into a store expression
有人知道我能做些什么来解决这个问题吗?
最佳答案
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/