首先簡單地完善一下前面提到的例子,程式碼如下:
//測試實體類
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!