首先简单地完善一下前面提到的例子,代码如下:
//测试实体类 public class Table { public int A; public int B; }
//独立条件: public class Field { public Logical Logical { get; set; } //与其它条件之间的逻辑关系 public Comparer Comparer { get; set; } //条件比较符 public Type DataType { get; set; } //数据类型 public string FieldName { get; set; } //字段名称 public object QueryValue { get; set; } //条件值 }
//条件组: public class Block { public Logical Logical { get; set; } //与其它条件组或独立条件之间的逻辑关系 public List<Field> Fields { get; set;}=new List<Field>(); public List<Block> Blocks { get;set; }=new List<Block>(); }
//逻辑 public enum Logical { And, Or, } //比较 public enum Comparer { Equal, GreatThan, LessThan, }
代码简单就不作多说明了,就是添加一个独立条件,两个子组,子组里分别包含两个独立条件,以描述等效于
SQL
=(Table1.A<3 OR Table1.A=3) Or (Table1.A>5 And Table1.B=3)) OR Table1.B>5
的查询子句。
Block CreaterDescriptor() { //SQL: (Table1.A<3 OR Table1.A=3) Or (Table1.A>5 And Table1.B=3)) OR Table1.B>5 var block = new Block() {Logical= Logical.Or}; block.Fields.AddRange(new[]{new Field(){ Comparer= Comparer.GreatThan, DataType= typeof(int), FieldName="B", Logical= Logical.Or, QueryValue=5}}); block.Blocks.AddRange(new [] { new Block(){ Logical= Logical.Or, Fields=new List<Field>(new Field[]{ new Field(){ Comparer= Comparer.LessThan, DataType=typeof(int), FieldName="A", QueryValue= 3}, new Field(){ Comparer= Comparer.Equal, DataType=typeof(int), FieldName="A", Logical= Logical.Or, QueryValue= 3} }), }, new Block(){ Logical= Logical.Or, Fields=new List<Field>(new Field[]{ new Field(){ Comparer= Comparer.GreatThan, DataType=typeof(int), FieldName="A", QueryValue= 5}, new Field(){ Comparer= Comparer.Equal, DataType=typeof(int), FieldName="B", Logical= Logical.And,QueryValue= 3} }), }, }); return block; }
至此,已经拿到查询条件描述对象,知道了需要以什么条件进行查询了,一下步就是如何其转换为查询委托。
先来个手动组装看看上篇的设想能不能行得通。
Expression<Func<Table,bool>> Manual() { //SQL: (Table1.A<3 OR Table1.A=3) Or (Table1.A>5 And Table1.B=3)) OR Table1.B>5 //老套路,先包装 var Table1 = new Table(); var p = Expression.Parameter(typeof(Table), "Table1"); //将5、3这两个常量包装成ConstantExpression: var num5 = Expression.Constant(5, typeof(int)); var num3 = Expression.Constant(3, typeof(int)); //将两个属性包装成MemberExpression。 var a = Expression.PropertyOrField(p, "A"); var b = Expression.PropertyOrField(p, "B"); //构造Table1.A<3: var ltA3 = Expression.LessThan(a, num3); //构造Table1.A=3: var eqA3 = Expression.Equal(a, num3); //构造Table1.A>5: var gtA5 = Expression.GreaterThan(a, num5); //构造Table1.A=5: var eqB3 = Expression.Equal(b, num3); //构造Table1.B>5: var gtB5 = Expression.GreaterThan(b, num5); //构造Table1.A<3 OR Table1.A=3 var expLtA3orEqA3 = Expression.OrElse(ltA3, eqA3); //构造Table1.A>5 && Table1.B=3 var expGtA5andEqB3 = Expression.AndAlso(gtA5, eqB3); //构造(Table1.A<3 OR Table1.A=3) Or (Table1.A>5 And Table1.B=3)) var expGtA5andEqA3_Or_expLtA3orEqA3=Expression.OrElse(expLtA3orEqA3,expGtA5andEqB3); //(Table1.A<3 OR Table1.A=3) Or (Table1.A>5 And Table1.B=3)) OR Table1.B>5 var result=Expression.OrElse(expGtA5andEqA3_Or_expLtA3orEqA3,gtB5); //结果要出来了 Expression<Func<Table,bool>> lambda=Expression.Lambda<Func<Table,bool>>(result,p); return lambda; }
手动组装好了,来测试验证一下:
//测试方法 void TestLambda(Expression<Func<Table,bool>> lambda) { var list = new List<Table> { new Table{A=6,B=2}, new Table{A=5,B=6}, new Table{A=2,B=3} } ; var my = list.Where(t => lambda.Compile()(t)).ToArray(); var linq = list.Where(t => ((t.A < 3 || t.A == 3) || (t.A > 5 && t.B == 3)) || t.B > 5).ToArray(); Debug.Assert(my.Length == linq.Length); for (var i = 0; i < my.Length; i++) { Debug.Assert(my[i] == linq[i]); } Console.WriteLine("Test_Ok"); }
//运行测试 void Main() { var lambda=Manual(); TestLambda(lambda ); }
经过上机运行,结果正确,OK!
但是,问题来了,这手动组装并不简单,稍不留神就容易写错,如果真这么用,就是浪费表情了。那么有没有自动的,不需要人工干预的方法?必须有,否则本系列文章还有什么可写的呢?
具体看下面代码,就不太过啰嗦的解释了,简单说明一下思路,拿到一个多层嵌套的条件组之后,先对直接的独立条件进行LambdaExpression逐个组装,串联起来,再逐个组装子条件组也串联起来,最后把独立条件和子组串联起来,如果子组里还有子组,进行逐层递归:
Expression<Func<T,bool>> CreaterQueryExpression<T>(Block block) { var param=Expression.Parameter(typeof(T),typeof(T).Name); return Expression.Lambda<Func<T,bool>>(CreateBlockExpr(block),param); Expression CreateFieldExpr(List<Field> fields) { var lastExp=default(Expression); foreach (var f in fields) { var member=Expression.PropertyOrField(param, f.FieldName); var value=Expression.Constant(f.QueryValue); var exp=f.Comparer switch { Comparer.GreatThan=>Expression.GreaterThan(member,value), Comparer.LessThan=>Expression.LessThan(member,value), _=> Expression.Equal(member,value), }; if (lastExp != default(Expression)) { exp= f.Logical switch { Logical.Or => Expression.OrElse(lastExp,exp), _=>Expression.AndAlso(lastExp,exp), }; } lastExp=exp; } return lastExp; } Expression CreateBlockExpr(Block block) { var lastExp=default(Expression); var exp=CreateFieldExpr(block.Fields); foreach (var sub in block.Blocks) { var subExp = CreateBlockExpr(sub); if (lastExp != default && subExp!=default) { subExp = sub.Logical switch { Logical.Or => Expression.OrElse(lastExp, subExp), _ => Expression.AndAlso(lastExp, subExp), }; } lastExp=subExp; } if (lastExp != default && exp!=default) { exp= block.Logical switch { Logical.Or => Expression.OrElse(exp, lastExp), _ => Expression.AndAlso(exp, lastExp), }; } return exp; } }
好,委托已经拿到。是否能正确实现查询意图呢?来测试一下:
// 运行测试 void Main() { var lambda=CreaterQueryExpression<Table>(CreaterDescriptor()); TestLambda(lambda); }
经上机运行,结果OK!