public static IQueryable<TEntity> Find<TEntity>(this IQueryable<TEntity> source, TEntity obj, bool isAnd) where TEntity : class { if (source == null) throw new ArgumentNullException("Source can't be null!!"); //获得所有property的信息 PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); Expression condition = null; //先构造了一个ParameterExpression对象,这里的c,就是Lambda表达中的参数。(c=>) //本变量被移出了foreach循环 ParameterExpression param = Expression.Parameter(typeof(TEntity), "c"); //遍历每个property foreach (PropertyInfo p in properties) { if (p != null) { Type t = p.PropertyType; //只支持value型和string型的影射 if (t.IsValueType || t == typeof(string)) { //如果不为null才算做条件 if (p.GetValue(obj, null) != null) { //SQL Server does not support comparison of TEXT, NTEXT, XML and IMAGE ,etc /**////Only support BigInt,Bit,Char,Decimal,Money,NChar,Real, ///Int,VarChar,SmallMoney,SmallInt,NVarChar,NVarChar(MAX),VarChar(MAX) Attribute attr = Attribute.GetCustomAttribute(p, typeof(ColumnAttribute)); if (attr != null) { string dbType = (attr as ColumnAttribute).DbType; if (dbType.Contains("Text") || dbType.Contains("NText") || dbType.Contains("Xml") || dbType.Contains("Image") || dbType.Contains("Binary") || dbType.Contains("DateTime") || dbType.Contains("sql_variant") || dbType.Contains("rowversion") || dbType.Contains("UniqueIdentifier") || dbType.Contains("VarBinary(MAX)")) { continue; } } //构造表达式的右边,值的一边 Expression right = Expression.Constant(p.GetValue(obj, null), p.PropertyType); //构造表达式的左边,property一端。 Expression left = Expression.Property(param, p.Name); //生成筛选表达式。即c.CustomerID == "Tom" Expression filter = Expression.Equal(left, right); if (condition == null) { condition = filter; } else { if (isAnd) condition = Expression.And(condition, filter); else condition = Expression.Or(condition, filter); } } } } } if (condition != null) { Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(condition, param); return source.Where(pred); } return source; }
public static IQueryable<TEntity> Find<TEntity>(this IQueryable<TEntity> source, TEntity obj) where TEntity : class { return Find<TEntity>(source,obj,true);