You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中Dynamic LINQ日期比较运算符不兼容报错如何解决

问题根因

你直接把DateTime类型变量拼接到Dynamic LINQ的查询字符串中时,DateTime默认输出的日期格式会被Dynamic LINQ解析器误认为是数值减法表达式,比如10/25/2024会被解析为10 - 25 - 2024,最终得到Int32类型的计算结果,因此出现DateTime和Int32类型不兼容的运算符报错。

修复方案

  • 方案1:显式标识日期值类型,避免解析错误
    给拼接的日期值加上DateTime.Parse标识,让Dynamic LINQ正确识别为日期类型:

    if(compare == "Greater")
    {
        where = String.Format("{0} > DateTime.Parse(\"{1}\")", 
            DueDate, 
            DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd"));                            
    }
    else if(compare == "Lesser")
    {
        where = String.Format("{0} < DateTime.Parse(\"{1}\")", 
            field, 
            DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd"));
    }
    
  • 方案2:使用参数化查询(更推荐)
    Dynamic LINQ原生支持参数占位符,直接把DateTime值作为参数传入即可,不需要处理格式转义,还能避免SQL注入风险:

    // 先统一解析出要比较的日期
    DateTime compareDate = DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
    // 拼接条件时用占位符代替实际值
    if(compare == "Greater")
    {
        where = $"{DueDate} > @0";
    }
    else if(compare == "Lesser")
    {
        where = $"{field} < @0";
    }
    // 执行查询时把日期参数传入
    var items = context.itemsGalore.Where(where, compareDate).ToList();
    

内容的提问来源于stack exchange,提问作者The_Outsider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:54:00