FineUI 官方论坛
标题:
分享一个EF 动态Lambda表达式查询类
[打印本页]
作者:
盼月亮
时间:
2015-1-10 11:18
标题:
分享一个EF 动态Lambda表达式查询类
本帖最后由 盼月亮 于 2015-1-10 13:44 编辑
[attach]7066[/attach][attach]7064[/attach][attach]7065[/attach]
自己用的EF动态查询,下拉框的条件是保存在数据库的,通过该类生成动态表达式查询。
/// <summary>
/// 查询表达式
/// </summary>
public static class SearchExpression
{
private static Expression ConditonToExpression(SearchCondition condition, Expression parameter, Type type)
{
Expression expr = null;
PropertyInfo pi = type.GetProperty(condition.Field);
Expression left = Expression.Property(parameter, pi);
object value = Convert.ChangeType(condition.Value, pi.PropertyType);//修改红色部分可支持多表(稍微思考就知道答案了,聪明的网友你想出来了吗?),上图已实现
Expression right = Expression.Constant(value);
switch (condition.Operator)
{
case "=":
expr = Expression.Equal(left, right);
break;
case "<":
expr = Expression.LessThan(left, right);
break;
case "<=":
expr = Expression.LessThanOrEqual(left, right);
break;
case ">":
expr = Expression.GreaterThan(left, right);
break;
case ">=":
expr = Expression.GreaterThanOrEqual(left, right);
break;
case "!=":
expr = Expression.NotEqual(left, right);
break;
}
return expr;
}
/// <summary>
/// 按条件查询
/// </summary>
/// <typeparam name="T">实体模型</typeparam>
/// <param name="conditions">过滤条件</param>
/// <returns>表达式</returns>
public static Expression<Func<T, bool>> FindByGroup<T>(List<SearchCondition> conditions)
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "r");
Expression body = null;
Type type = typeof(T);
if (conditions.Count > 0)
{
body = ConditonToExpression(conditions[0], parameter, type);
for (int i = 1; i < conditions.Count; i++)
{
Expression right = ConditonToExpression(conditions
, parameter, type);
body = conditions[i - 1].Relation.ToUpper().Equals("AND") ?
Expression.And(body, right) :
Expression.Or(body, right);
}
}
if (body != null)
{
Expression<Func<T, bool>> expr = Expression.
Lambda<Func<T, bool>>(body, parameter);
return expr;
}
return null;
}
}
作者:
zy32002
时间:
2015-1-10 12:33
{:soso_e179:}
欢迎光临 FineUI 官方论坛 (https://fineui.com/BBS/)
Powered by Discuz! X3.4