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);
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);
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.anti-gravitydesign.com