views:

972

answers:

3

I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0.

It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. The very simple test code is

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.

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.

+2  A: 

I think that you can convert the searchString to a DateTime and pass it in as a parameter to the dynamic where method itself.

itmes = items.Where( string.Format( "{0} > @0", searchField ),
                     DateTime.Parse( searchString ) );
tvanfosson
Thanksitems = items.Where(string.Format("{0} > @0", searchField), new DateTime(2001, 1, 15));worked great
Matthew Hood
A: 

What if the entire lambda is being created dynamically (we'll go with equals instead of greater than) and the type is not known? In that case you can't use DateTime.Parse in the where parameters. If you try to pass in the DateTime object, Dynamic LINQ interprets it as an int32 type. Could you possibly do it by converting the ticks or milliseconds of the DateTime first and comparing that?

kappasims
A: 

I also have the same problem. I'm buildig a whole string dynamicly, and don't know how much parameters I have. Is it possible to write it like this: dc.INVOICEs.Where("DATE_UNTILL > \"2010/04/13\"").

Dimitri
I would use the same approach as above and parse the string to a DateTime using ParseExact to specify the format. For multiple entries loop through building a parameter array and incrementing @0 @1 etc in your query string. If you need more help probably better to ask a new question.
Matthew Hood