【问题标题】:System.Linq.Dynamic and DateTimeSystem.Linq.Dynamic 和 DateTime
【发布时间】:2010-11-26 06:24:03
【问题描述】:

我正在使用 System.Linq.Dynamic 从 .Net MVC 1.0 中的 ajax 调用中自定义 where 子句。

它适用于字符串、int 等,但不适用于 DateTime,我得到异常无法将 String 与 DateTime 进行比较。非常简单的测试代码是

items = items.Where(string.Format(@" {0} > {1}{2}{1} ", searchField, delimiter, searchString));

其中 searchField 将是例如 start_date 并且数据类型是 DateTime,分隔符是 "(也没有尝试过)并且 searchString 将是 01-Jan-2009(也尝试过 01/01/2009)并且 items 是来自 LinqToSql 的 IQueryable。

有没有办法在动态where中指定数据类型,或者有更好的方法。它目前已经在使用一些反射来确定需要什么类型的分隔符。

【问题讨论】:

  • 当一个问题有大量赞成票的答案时,它总是把我搞糊涂,但问题本身却有 0 票赞成。瘸。好问题,我来到这里是因为我需要同样的东西!给你点赞,好先生!

标签: c# linq dynamic system.linq.dynamic


【解决方案1】:

我认为您可以将 searchString 转换为 DateTime 并将其作为参数传递给动态 where 方法本身。

itmes = items.Where( string.Format( "{0} > @0", searchField ),
                     DateTime.Parse( searchString ) );

【讨论】:

  • 感谢 items = items.Where(string.Format("{0} > @0", searchField), new DateTime(2001, 1, 15));效果很好
【解决方案2】:
yourlist.Where("PostDate > DateTime(2013, 07, 24)");

【讨论】:

    【解决方案3】:

    我使用 Convert.ToDateTime 来解决这个问题,因为我正在做类似于 Kappasims 的事情

    items = items.Where(string.Format("{0} > Convert.ToDateTime(\"{1}\")", searchField, searchValue); 
    

    【讨论】:

    • 我已经在很多地方看到了这个建议,但它对我不起作用——失败了 LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)'
    • 我对这个建议有同样的问题。在哪个 sql server 中运行?
    【解决方案4】:

    如果您只想使用Where([string]) 格式执行此操作,而不传递其他参数,则可以使用日期格式Date(yyyy, mm, dd)。所以我能够通过这样做来完成这项工作

    items.Where("DateAdded > Date(2013, 06, 18)")
    

    有一个完整的规范 here 概述了解析和有效用途。

    【讨论】:

      【解决方案5】:

      如果整个 lambda 是动态创建的(我们将使用等于而不是大于)并且类型未知怎么办?在这种情况下,您不能在 where 参数中使用 DateTime.Parse。如果您尝试传入 DateTime 对象,Dynamic LINQ 会将其解释为 int32 类型。您可以通过先转换 DateTime 的刻度或毫秒并进行比较来做到这一点吗?

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 2017-04-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-30
        • 1970-01-01
        • 2013-12-14
        • 2016-03-18
        • 1970-01-01
        相关资源
        最近更新 更多