我正在形成如下的字符串表达式。
string Condition = " it.person_id = " + personId.ToString();
if (lstPersonFields != null)
{
foreach (var field in lstPersonFields )
{
string fieldCondition = " And it." + field.FieldName.ToString();
if (field.FieldCondition == "Contains")
{
fieldCondition = fieldCondition + " Like '%" + field.FieldValue.ToString() + "%'";
}
else if (field.FieldCondition == "Equals")
{
fieldCondition = fieldCondition + " = '" + field.FieldValue.ToString()+"'";
}
Condition = Condition + fieldCondition;
}
}
var personSearch = FullPersonlst.Where(Condition).ToList();
上面的代码在类似搜索中的日期时间值之外正常工作,并为日期时间字段抛出错误,如
Like arguments must be of string type
如何搜索日期时间字段?
答案 0 :(得分:1)
要做到这一点,动态lambda表达式将类似于:
var arg = Expression.Parameter(typeof(Person), "it");
var body = Expression.Equal(
Expression.PropertyOrField(arg, "PersonId"),
Expression.Constant(personId));
if (lstPersonFields != null)
{
foreach (var field in lstPersonFields)
{
var member = Expression.PropertyOrField(arg, field.FieldName);
switch (field.FieldCondition)
{
case "Contains":
body = Expression.AndAlso(body,
Expression.Call(typeof(SqlMethods), "Like", null,
member,
Expression.Constant("%" + field.FieldValue + "%")));
break;
case "Equals":
body = Expression.AndAlso(body,
Expression.Equal(
member,
Expression.Constant(field.FieldValue)));
break;
}
}
}
var lambda = Expression.Lambda<Func<Person,bool>>(body, arg);
var personSearch = FullPersonlst.Where(lambda).ToList();
答案 1 :(得分:0)
如错误所示,您不应该对非字符串值使用like。这也没有意义。如果要搜索特定日期时间,请使用datetime = value。对于在某个时间范围内搜索,您可以在两者之间使用。您需要检查要搜索的属性类型,并使用适当的方式在查询中拟合类型。
就个人而言,我永远不会使用这样的'动态查询创建者'。