Dynamic LINQ with datetime

c# dynamic-linq entity-framework

Question

I am trying to write a simple linq select query, where in the where clause the value is taken from a text box. I am having problem in case of datetime values. Now this works:

 var rawData = contextSearch.GetType().GetProperty(TableName).GetValue(contextSearch, null);
 truncatedData = ((IQueryable<object>)rawData).Where(columnName + ">=@0", DateTime.Parse(txtCrudSearch.Text)).ToList();

this also works for <=, but I need to find records for exactly the given date. So, when I try this:

truncatedData = ((IQueryable<object>)rawData).Where(columnName + "=@0", DateTime.Parse(txtCrudSearch.Text)).ToList();

It doesn't work. Why? How can I get this to work? FYI: columnname is taken from combobox dynamically and I'm using entity framework.

1
1
2/9/2015 2:02:56 PM

Accepted Answer

If you only want to compare the date and ignore time, try this:

var parsedDt = DateTime.Parse(txtCrudSearch.Text);
var nextDay = parsedDt.AddDays(1);

truncatedData = ((IQueryable<object>)rawData)
                 .Where(columnName + ">= @0 && " + columnName + " < @1", parsedDt, nextDay)
                 .ToList();

(This solution is based on @algreat answer)

0
5/23/2017 12:27:20 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow