I have been banging my head on this problem for sometime. There are some similar cases, but the solutions weren't applicable on my case.
I have a method that returns filter query in string format. The method has logic for different data types, sets correct values, column names etc.
string filterQuery = GetFilterQuery(params);
rows = rows.Where(filterQuery);
My problem is that I have Nullable DateTime
in the database and I have String
representation in the code side.
I have tried following queries (String
representation might be wrong currently):
"BirthDate.ToString() = \"16.2.2012 22:00:00\""
Result: Methods on type 'DateTime?' are not accessible
"BirthDate.Value.ToString() = \"16.2.2012 22:00:00\""
Result: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
"BirthDate == null ? 1=1 : (DateTime)BirthDate.ToString() = \"16.2.2012 22:00:00\""
Result: '.' or '(' expected
Any ideas how to solve the problem?
Update (more source code added about query generation)
var filterQueries = query.GridFilteringOptions.filters
// remove filters that doesn't have all the required information
.Where(o => o.name != string.Empty && o.value != string.Empty && !string.IsNullOrEmpty(o.type))
// remove filters that are filtering other tables than current
.Where(o => o.table == tableName)
.Select(filter => filter.ResolveQuery()).ToList();
if (filterQuery.Any())
{
var filterQuery = string.Join(" And ", filterQueries);
rows = rows.Where(filterQuery);
}
And here is a class Filter and methods are related to this context
public string ResolveQuery()
{
if (type == "Int64")
{
return ResolveInteger();
}
else if(type == "String")
{
return ResolveString();
}
else if(type == "DateTime")
{
return ResolveDateTime();
}
else
{
return string.Empty;
}
}
private string ResolveDateTime()
{
DateTime result = new DateTime();
if (DateTime.TryParse(this.value, out result))
{
return string.Format("{0}.ToString() = \"{1}\"", this.name, result.ToUniversalTime());
}
return string.Empty;
}
private string ResolveString()
{
switch (@operator)
{
default:
return string.Format(@"{0}.StartsWith(""{1}"")", this.name, this.value);
}
}
private string ResolveInteger()
{
string tmp = this.name;
switch (@operator)
{
case -1:
return string.Empty;
case 0:
tmp += "<";
break;
case 1:
tmp += "=";
break;
case 2:
tmp += ">";
break;
default:
return string.Empty;
}
tmp += value;
return tmp;
}