在LINQ asp.net MVC中将可空日期时间转换为字符串时出错

时间:2016-10-11 13:32:31

标签: c# asp.net asp.net-mvc linq datetime

我正在开发一个带有Kendo UI的asp.net MVC系统。我必须从View中的过滤器按钮向控制器发送“日期”并过滤LINQ。我用了这段代码:

public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, string filterDate)
        {
            DateTime _temp;
            if (!DateTime.TryParse(filterDate, out _temp))
                _temp = DateTime.Now;

            return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
                .Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy"))
                .Select(l => new LogAdminInfo
                {
                    Id = l.Id,
                    Message = l.Message,
                    MessageTemplate = l.MessageTemplate,
                    Level = l.Level,
                    TimeStamp = l.TimeStamp,
                    Exception = l.Exception,
                    Properties = l.Properties,
                    LogEvent = l.LogEvent,
                })
                .ToDataSourceResult(request));
        }

但它给了我一个错误的“.Where”。你应该知道TimeStamp字段是“datetime?”可以约会的日期时间。

我收到此错误:

  

LINQ to Entities无法识别方法'System.String   ToString()'方法,并且此方法无法转换为商店   表达

我该如何修复错误?

3 个答案:

答案 0 :(得分:1)

替换

.Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy"))

.Where(f =>  DbFunctions.TruncateTime(f.TimeStamp) == _temp)

答案 1 :(得分:1)

错误很明显,LINQ to Entities不支持ToString方法,您应该使用其他方法比较日期。

根据您的代码,我假设您只对DateTime的日期部分感兴趣以进行比较,因此我建议您尝试DbFunctions.TruncateTime Method

Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))

答案 2 :(得分:0)

    var tempDate = _temp.ToString("dd.MM.yyyy")    
    Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)    
.Select(l => new LogAdminInfo
                    {
                        Id = l.Id,
                        Message = l.Message,
                        MessageTemplate = l.MessageTemplate,
                        Level = l.Level,
                        TimeStamp = l.TimeStamp.Value.ToString("dd.MM.yyyy"),
                        Exception = l.Exception,
                        Properties = l.Properties,
                        LogEvent = l.LogEvent,
                    }).Where(l => l.TimeStamp = tempDate).Select(l)
                    .ToDataSourceResult(request));