【发布时间】:2012-02-14 08:51:25
【问题描述】:
一段时间以来,我一直在努力解决这个问题。有一些类似的案例,但解决方案不适用于我的案例。
我有一个以字符串格式返回过滤器查询的方法。该方法具有针对不同数据类型的逻辑,设置正确的值、列名等。
string filterQuery = GetFilterQuery(params);
rows = rows.Where(filterQuery);
我的问题是我在数据库中有Nullable DateTime,而我在代码端有String 表示。
我尝试了以下查询(String 表示目前可能是错误的):
"BirthDate.ToString() = \"16.2.2012 22:00:00\""
结果:“日期时间”类型的方法?无法访问
"BirthDate.Value.ToString() = \"16.2.2012 22:00:00\""
结果:LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式。 p>
"BirthDate == null ? 1=1 : (DateTime)BirthDate.ToString() = \"16.2.2012 22:00:00\""
结果:'.'或“(”预期
有什么办法解决这个问题吗?
更新(添加了更多关于查询生成的源代码)
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);
}
这是一个类过滤器,方法与此上下文相关
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;
}
【问题讨论】:
标签: c# linq linq-to-entities dynamic-linq