1 [Fact] 2 public void TestQuery3() 3 { 4 var helper = new TypeInfoHelper<Order>(); 5 //得到訂單集合中的第一張訂單,用於以後的單元測試驗證 6 var findOrder = orders.First(); 7 //定義一個查詢,條件爲訂單主鍵等於前面獲取的訂單對象的主鍵值 8 var query = new Query(typeof(Order)) 9 { 10 RootExpression = helper.GetProperty(p => p.BillId).EqualTo(findOrder.BillId) 11 }; 12 /*第一種編譯方式*/ 13 //定義一個生成Lambda表達式的編譯器對象 14 var compiler = new LambdaExpressionCompiler<Order>(query); 15 //將查詢對象編譯爲Linq表達式 16 var expression = compiler.Compile(); 17 //對訂單集合執行linq查詢 18 var items = orders.Where(expression.Compile()).ToList(); 19 //驗證查詢結果中僅包含一張訂單,且訂單編號與參照訂單的編號相同 20 Assert.Equal(items.Count, 1); 21 Assert.Equal(items.First().BillNo, findOrder.BillNo); 22 23 /*第二種編譯方式*/ 24 //定義一個生成SQL腳本的編譯器對象 25 var sqlCompiler = new SqlWhereClauseCompiler(query) { GenSelectPart = true }; 26 //將查詢對象編譯爲SQL腳本 27 var sql = sqlCompiler.Compile(); 28 Console.WriteLine(sql); 29 //執行sql腳本 30 var reader = dbHelper.Read(sql, sqlCompiler.ParameterValues); 31 //驗證返回的結果中只有一條記錄,且訂單編號與參照訂單的編號相同 32 Assert.Equal(reader.Read(), true); 33 Assert.Equal(findOrder.BillNo, reader["BillNo"]); 34 Assert.Equal(reader.Read(), false);//驗證只能執行讀取一次操做 35 }
SELECT * FROM xzcOrder AS o WHERE (o.BillNo LIKE 'PO%' OR NOT o.BillDate >= '2014-1-1 0:00:00' ) AND EXISTS(SELECT 1 FROM supplier WHERE supplier.Id=o.SupplierId AND supplier.Code LIKE '%X%') AND o.Invalid = 0 AND EXISTS(SELECT 1 FROM Items AS d WHERE d.BillId=o.BillId AND EXISTS(SELECT 1 FROM Product AS p WHERE p.Id=d.ProductId AND p.Unit = '部')) AND EXISTS(SELECT 1 FROM Items AS d WHERE d.BillId=o.BillId AND d.Qty < o.TotalQty)
相應的C#代碼html
1 var helper = new TypeInfoHelper<Order>(); 2 var query = new Query(typeof(Order)) 3 { 4 RootExpression = helper.GetProperty(p => p.BillNo).StartsWith("PO") //單號以PO打頭 5 .Or(helper.GetProperty(p => p.BillDate).GreaterThanOrEqualTo(new DateTime(2014, 1, 1)).Not())//訂單日期 不 大於等於 2014-1-1 6 .Unitary() //上面兩個條件設爲獨立總體,即用()號包圍 7 .And(helper.GetProperty(p => p.Supplier.Code).Contains("X"))//供應商編碼中包含字符"X" 8 .And(helper.GetProperty(p => p.Invalid).EqualTo(false)) //訂單失效標誌爲否 9 .And(helper.GetProperty(p => p.Items.FirstOrDefault().Product.Unit).EqualTo("部")) //訂購產品的計量單位爲"部" 10 .And( 11 //訂單明細中各項訂購數量小於訂單總訂購數量,僅爲測試,無實際意義 12 helper.GetProperty(p => p.Items.FirstOrDefault().Qty) 13 .LessThan(helper.GetProperty(p => p.TotalQty))) 14 }; 15 List<Order> items; 16 var sqlCompiler = new SqlWhereClauseCompiler(query) { GenSelectPart = true }; 17 var sql = sqlCompiler.Compile(); 18 Console.WriteLine(sql);