首页 > 解决方案 > 如何在 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.

如何将字符串转换为日期并进行比较?

标签: c#sqlentity-frameworklinq

解决方案


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);

结果测试:

在此处输入图像描述


推荐阅读