Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic LINQ DateTime Comparison String Building - Linq To Entities

I'm using the dynamic LINQ library by Scott Guthrie together with Entity Framework and C#.

I have to build my where string into a variable based on several factors and then pass the string variable to the where clause. For some reason, this will work:

ContactList = ContactList.Where("DateAdded >= @0", DateTime.Parse("12/1/2012"));

But this will not work

string WhereClause = string.Format("DateAdded >= {0}", DateTime.Parse("12/1/2012"));
ContactList = ContactList.Where(WhereClause);

As mentioned, I need to use it in the version of passing the variable. Anyone know why the second doesn't work?

Thanks in advance!

like image 844
Ricketts Avatar asked Jan 02 '13 17:01

Ricketts


3 Answers

I was able to get it working with a slightly different string format using the information here.

Doing this worked fine for me:

ContactList.Where("DateAdded >= DateTime(2013, 06, 18)")

Note this does not work at all with DateTimeOffset columns.

like image 143
Richard Rout Avatar answered Sep 18 '22 15:09

Richard Rout


It seems what I was trying to do is not possible with the current DynamicLINQ library. The reason it didn't work was well outlined below by Tilak.

My solution was to modify the DynamicLINQ library to allow the query to be written as a string and passed to the where clause for Date/Time datatypes. The modification was found here by Paul Hatcher: LINQ TO SQL, Dynamic query with DATE type fields

like image 22
Ricketts Avatar answered Sep 17 '22 15:09

Ricketts


ObjectQuery.Where overload accepts 2 parameters.

  1. string predicate
  2. params ObjectParameter[] parameters

In your first example, Where builds the query (where clause) using ObjectParameter parameters (using Name, Type and Value of ObjectParameter)

In your second example, whatever is passed is treated as final where clause (no internal conversion based on datatype of passed parameters done).

like image 23
Tilak Avatar answered Sep 21 '22 15:09

Tilak