c# - 如何在 Linq Where 子句中将 Char 转换为 Datetime
问题描述
我需要帮助将 char 类型转换为 dateTime 并进行比较。
我在成本表中有 [MonthYYYYMM] 作为 char 类型
[MonthYYYYMM] [char](8) NOT NULL,
我试过这个 Linq 表达式看起来像这样但不起作用
var ProjectList = Context.Project.AsNoTracking()
.Include(c=> c.Cost)
.Where(p => p.Cost.Any(c=> DateTime.ParseExact(c.MonthYYYYMM, "yyyyMM", CultureInfo.InvariantCulture) <= request.ToDate
&& DateTime.ParseExact(c.MonthYYYYMM, "yyyyMM", CultureInfo.InvariantCulture) >= request.FromDate)
.ToListAsync();
我收到这个错误
> Error Content: System.InvalidOperationException: The LINQ expression
> 'DbSet<Cost>
> .Where(c => EF.Property<Nullable<int>>((EntityShaperExpression:
> EntityType: Project
> ValueBufferExpression:
> (ProjectionBindingExpression: EmptyProjectionMember)
> IsNullable: False
> ), "ID") != null && EF.Property<Nullable<int>>((EntityShaperExpression:
> EntityType: Project
> ValueBufferExpression:
> (ProjectionBindingExpression: EmptyProjectionMember)
> IsNullable: False
> ), "ID") == EF.Property<Nullable<int>>(c, "ProjectID"))
> .Any(c => DateTime.ParseExact(
> s: c.MonthYYYYMM
> format: "yyyyMM",
> provider: __InvariantCulture_0) <= __request_ToDate_1 && DateTime.ParseExact(
> s: c.MonthYYYYMM
> format: "yyyyMM",
> provider: __InvariantCulture_0) >= __request_FromDate_2)' could not be translated.
如何将字符串转换为日期并进行比较?
解决方案
DateTime.ParseExact(x, "yyyyMM", CultureInfo.InvariantCulture)
无法翻译。不可能在 aWhere
的a 中使用方法IQueryable
,因为Linq
无法SQL
知道如何将您的方法转换为 SQL。你可以用它AsEnumerable()
来实现你所有的类型。
var CostList = Context.Cost.AsEnumerable().Where(c =>
DateTime.ParseExact(c.MonthYYYYMM, "yyyyMM",CultureInfo.InvariantCulture) <= ToDate
&& DateTime.ParseExact(c.MonthYYYYMM, "yyyyMM", CultureInfo.InvariantCulture) >= FromDate);
return Json(CostList);
结果测试:
推荐阅读
- python-3.x - Keras LSTM 层值错误:维度必须相等,但分别为 17 和 2
- linux - Caddy V2 IP 白名单
- javascript - 使用 AJAX + Javascript 将图像上传到 PHP 网站上的 IMGBB (Bootstrap)
- python - 压缩文件夹中的特定文件 - 找不到 zip 文件
- django - django+gunicorn+nginx 在提供静态文件时给出 404
- javascript - 无法在量角器 e2e 测试中找到 MatSnackBar 元素
- python - 子进程不会捕获 powershell 输出
- docker - LC_ALL:无法更改语言环境 (en_US.UTF-8) newaliases:在 sSMTP 中,别名是从纯文本文件中读取的
- cmder - 如果文件夹的名称中有空格并且我不能/不想更改它的名称,如何键入文件的路径?
- php - Firebase - PHP - 错误解码消息:无法处理消息上的未知字段collection_Id