LINQ and Dynamic Query – Comparing DateTime value

In one of our development, we end up with the situation that needs to check the DateTime value in Dynamic LINQ query. Trying different ways out there and googling a bit, finally got some useful references that helped us to resolve the same

Hope, you would love reading!

 

Example:

TestEntities te = new TestEntities();

string dateString = “12/01/2010”;

 

Used the following overload for “.Where” :

# 1:

IQueryable<T>.Where(Expression<Func<State, bool>> predicate)

var dateTest = te.SiteLogs

.Where(String.Format(“it.TimeStamp >= DATETIME ‘{0}'”, Convert.ToDateTime(dateString).ToString(“yyyy-MM-dd HH:mm”)))

.Select(“it.IPAddress”);

 

# 2:

IQueryable.Where(string predicate, params object[] values)

var dateTest1 = te.SiteLogs

.Where(“it.TimeStamp >= @0”,  Convert.ToDateTime(dateString))

.Select(“it.IPAddress”);

 

Observations:

In # 1,

  • We need to say the “Time” format also, that is compulsory. Otherwise it would throw an error as well.  And again, the syntax with “DATETIME” is wired 🙂
  • The resultant date format should be “yyyy-MM-dd “

 

In # 2,

Its clean and simple. I like this syntax. Here you can add any number of Params like @0, @1 & so on

 

References:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

http://msdn.microsoft.com/en-us/library/bb399176.aspx

Advertisements

2 Comments »

  1. 1
    Fabio Says:

    Finally the answers to my questions! Thank you!!!


RSS Feed for this entry

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: