c# - 我如何比较和搜索字符串和日期时间 C#

标签 c# asp.net-mvc linq datetime

我使用比较字符串创建了一个简单的搜索,例如:

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.Title.Contains(searchWord) }, a => a.ArticleCategory);

并且工作正常;但我想在 datetime(date) 中搜索,我写了不同的代码:

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.InsertDate ==DateTime.Parse(searchWord) }, a => a.ArticleCategory);

articles = _service.ArticleRepository.GetAll(id, new Expression<Func<Article, bool>>[] { x => x.InsertDate.ToString("yyyyMMdd").Contains(searchWord) }, a => a.ArticleCategory);

给我一​​个错误:

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.

From this line int count = _db.Count();

我如何通过将日期作为字符串输入(以不同的格式,如:2017/8/5 或 05/05/2017 或 2017-8-5 或...)来比较字符串和日期,甚至输入一个数字(搜索所有有数字的日期)?

最佳答案

当执行 LINQ 查询时,它将转换为等效的 SQL 语句。 DateTime.Parse 是一种 C# 方法,可将字符串转换为其对应的 DateTime。没有相应的 SQL 等价物可以这样做。

您需要在 LINQ 查询之前创建一个 DateTime 对象并使用它。

var d = DateTime.Parse(searchWord);
var result= someEntityCollection.Where(a =>a.CreatedTime==d));

如果 CreatedTime 是一个 DateTime 字段,则比较也将包括时间戳。这意味着,它不会简单地给出那个日期的记录,而是那个日期和那个特定时间部分的记录

如果您尝试过滤特定日期(没有时间)的记录,您可以使用 DbFunctions.TruncateTime 辅助方法来完成此操作

var d = DateTime.Parse(searchWord);
var result= someEntityCollection.Where(a => 
          DbFunctions.TruncateTime(a.CreatedTime)== DbFunctions.TruncateTime(d.Date))

DbFunctions.TruncateTime 辅助方法在 System.Data.Entity 命名空间内定义。因此,请确保您有一个 using 语句来使用它。

using System.Data.Entity;

此外,使用 DateTime.ParseExactTryParseExact 格式比使用 DateTime.Parse

更安全
var d = DateTime.ParseExact(searchWord, "dd/MM/yyyy", CultureInfo.InvariantCulture);

关于c# - 我如何比较和搜索字符串和日期时间 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47240108/

相关文章:

c# - 为什么 TcpListener 从不接受 TcpClient?

c# - 值类型的依赖注入(inject)

asp.net-mvc - 将自定义错误从 JsonResult 方法返回到 ajax post 错误函数,并将其显示在验证摘要下

c# - 如何从 LINQ 中的列列表中选择非空值

c# - 如何在 C# 中将对象[,] 转换为数据表

c# - 如何将 JSON 对象作为参数从 Postman 传递到 ASP.NET WEB API

c# - 用户输出缓存。我注销时的错误

c# - 如何像在 stackoverflow 中那样执行 OpenId 实现

c# - 使用 linq 对嵌套列表进行分组

linq - 使用 LINQ 对多列进行分组和聚合