简体   繁体   English

System.Linq.Dynamic和DateTime

[英]System.Linq.Dynamic and DateTime

I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0. 我正在使用System.Linq.Dynamic在.Net MVC 1.0中执行ajax调用的自定义where子句。

It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. 它适用于字符串,int等但不适用于DateTime,我得到的异常无法将String与DateTime进行比较。 The very simple test code is 非常简单的测试代码是

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

Where searchField will be for example start_date and the data type is DateTime, delimiter is " (tried with nothing as well) and searchString will be 01-Jan-2009 (tried with 01/01/2009 as well) and items is an IQueryable from LinqToSql. 其中searchField将是例如start_date,数据类型是DateTime,分隔符是“(没有尝试过),searchString将是2009年1月1日(也在01/01/2009尝试过),并且items是一个IQueryable来自LinqToSql。

Is there a way of specifying the data type in a dynamic where, or is there a better approach. 有没有办法在动态中指定数据类型,或者有更好的方法。 It is currently already using some reflection to work out what type of delimiter is required. 它目前已经使用一些反射来确定需要什么类型的分隔符。

I think that you can convert the searchString to a DateTime and pass it in as a parameter to the dynamic where method itself. 我认为您可以将searchString转换为DateTime并将其作为参数传递给动态where方法本身。

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

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

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

If you want to do this with just the Where([string]) format, not passing in other paramaters, you can use the date format Date(yyyy, mm, dd) . 如果您只想使用Where([string])格式,而不是传递其他参数,则可以使用日期格式Date(yyyy, mm, dd) So I was able to get this working by doing 所以我能够做到这一点

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

There is a full spec here that outlines the parsing and valid uses. 有一个完整的规格在这里 ,概述了解析和有效使用。

What if the entire lambda is being created dynamically (we'll go with equals instead of greater than) and the type is not known? 如果动态创建整个lambda(我们将使用equals而不是大于)并且类型未知,该怎么办? In that case you can't use DateTime.Parse in the where parameters. 在这种情况下,您不能在where参数中使用DateTime.Parse。 If you try to pass in the DateTime object, Dynamic LINQ interprets it as an int32 type. 如果您尝试传入DateTime对象,Dynamic LINQ会将其解释为int32类型。 Could you possibly do it by converting the ticks or milliseconds of the DateTime first and comparing that? 您可以通过首先转换DateTime的滴答滴答或毫秒数并比较它来实现吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM