1,用object的查詢是什么?
我們可以簡單的舉這么一個例子。我們到公安局查找一個人。首先,我們會給出他的一些特征,比如,身高多少,年齡多少,性別,民族等。那么,我們把這個人的一些特征輸入電腦。我們希望,電腦能給我們返回這個人的信息。而實際上,有相同特征的人太多了,常常返回一個集合。那讓我們把這個過程抽象到程式里。我們需要new出來一個對象。這個對象包含了我們能知道的基本信息。而后,把這個對象傳給Linq To Sql,等待返回結果。
根據這些基本的需求,我們來定義下面的函數,為了實現這個函數對任何實體都是有用的,我們把它定義為generic的。為了不破壞Linq To Sql延遲加載的規矩,我們把它的返回類型定義為IQueryable。如下:
public IQueryable<TEntity> Find<TEntity>(TEntity obj) where TEntity : class
NorthwindDataContext db = new NorthwindDataContext(); //先new出一個對象 Customer c = new Customer(); //添入我們知道的最基本的信息,可以從ui獲得 c.City = "London"; c.Phone = "23236133"; //call函數find返回結果 var q = db.Find<Customer>(c);
Linq To Sql支持用戶動態生成lambda表達式。本文中所實現的方法,正是反射加lambda動態表達式。我們先來看如何動態生成lambda表達式。在 Linq 中,lambda表達式會首先轉化為Expression Tree,本文并不詳解Expression Tree。Expression Tree是lambda表達式從code的形式轉化為data的結果,是一種更高效的在內存中的數據結構。比如:
Func<int,int> f = x => x + 1; // Code Expression<Func<int,int>> e = x => x + 1; // Data
// 先構造了一個ParameterExpression對象,這里的c,就是Lambda表達中的參數。(c=>) ParameterExpression param = Expression.Parameter(typeof(TEntity), "c"); //構造表達式的右邊,值的一邊 Expression right = Expression.Constant(p.GetValue(obj, null)); //構造表達式的左邊,property一端。 Expression left = Expression.Property(param, p.Name); //生成篩選表達式。即c.CustomerID == "Tom" Expression filter = Expression.Equal(left, right); //生成完整的Lambda表達式。 Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param); //在這里,我們使用的是and條件。 query = query.Where(pred);
因為我們采用了模板,也就是說,我們并不知道傳進來的對象會有那些property,那反射在這里就提供一個很好的方法。我們可以通過反射去遍歷每一個property,只有判斷出該property的值不為null時,才將其視為條件。該函數完整的代碼如下:
public IQueryable<TEntity> Find<TEntity>(TEntity obj) where TEntity : class { //獲得所有property的信息 PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); //構造初始的query IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>(); //遍歷每個property foreach (PropertyInfo p in properties) { if (p != null) { Type t = p.PropertyType; //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。 if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[]) || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument) || t == typeof(System.Data.Linq.Binary)) { //如果不為null才算做條件 if ( p.GetValue(obj, null) != null) { ParameterExpression param = Expression.Parameter(typeof(TEntity), "c"); Expression right = Expression.Constant(p.GetValue(obj, null)); Expression left = Expression.Property(param, p.Name); Expression filter = Expression.Equal(left,right); Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param); query = query.Where(pred); } } } } return query; }
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/