I want to filter dates range. I'm using the dynamic LINQ library. I have to build my where string into a variable based on several factors and then pass the string variable to the where clause.
In my ASP.NET MVC project I wrote a helper.
private string GetFilterCondition(string filterCondition, string filterDataField, string filterValue)
{
switch (filterCondition)
{
case "CONTAINS":
return " " + filterDataField + ".Contains(\"" + filterValue + "\")";
case "GREATER_THAN_OR_EQUAL":
return " " + filterDataField + " >= " +"\"" + filterValue + "\"";
case "LESS_THAN_OR_EQUAL":
return " " + filterDataField + " <= " + "\"" + filterValue + "\"";
}
return "";
}
And I used parameter in query which I've passed from the ASP.NET MVC project;
public int GetFilteredCount(string searchValue)
{
var filteredRecords = 0;
try
{
var query = DB.Categories.AsQueryable();
var totalRecords = query.Count();
if (!string.IsNullOrEmpty(searchValue))
{
searchValue = searchValue.Trim();
query = query.Where(searchValue);
}
filteredRecords = query.Count();
}
catch (Exception e){}
finally
{
DestroyDbContext();
}
return result;
}
When filtering date range ("GREATER_THAN_OR_EQUAL", "LESS_THAN_OR_EQUAL"), I get an error:
Operator '>=' incompatible with operand types 'DateTime' and 'String'
Please note, that with 'contains' works.
I uploaded picture to see what looks like searchvalue parameter
I rewrote GetFilterCondition function like this:
case "GREATER_THAN_OR_EQUAL":
return string.Format(" {0} >= DateTime.Parse(\"{1}\")", filterDataField, filterValue);
case "LESS_THAN_OR_EQUAL":
return string.Format(" {0} <= DateTime.Parse(\"{1}\")", filterDataField, filterValue);
after executed filteredRecords = query.Count() throws this error:
LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression