EFCore 使用反射 根据实体的属性动态生成Expression进行查询

EFCore 的查询语法是:

Expression<Func<T,bool>> condition = x=>x.ClubId==1 ;
dbContext.Set<T>().Where(condition).ToList();

而我想通过传入一个T实体,根据T被赋值的属性来生成condition,用了反射和表达式树。不知道有没有大神告诉下其他的办法。

service层

public List<PlayersEntity> GetPlayers(PlayersEntity queryModel)
 {
       //获取类的属性
       PropertyInfo[] properties = queryModel.Players.GetType().GetProperties();
       BinaryExpression condtion = null;
       //Expression<Func<PlayersEntity, bool>> expression;
       var param = Expression.Parameter(typeof(PlayersEntity), "x"); //x=>
       //遍历属性
       foreach (PropertyInfo property in properties)
       {
           var value = property.GetValue(queryModel);
           //空值判断
           if (value == null)
               continue;
           if (int.TryParse(value.ToString(), out int temp) && value.ToString() == "0")
               continue;
           if (string.IsNullOrEmpty(property.GetValue(queryModel).ToString()))
               continue;

           //表达式树的构建
           MemberExpression left = Expression.Property(param , property);  //x.name
           ConstantExpression right = Expression.Constant(value, property.PropertyType); // value
           BinaryExpression be = Expression.Equal(left, right); //x=>x.name == value
           if (condtion == null)
           {
               condtion = be;
           }
           else
           {
               //拼接表达式树
               condtion = Expression.And(condtion, be);
           }
       }
       //生成表达式树
       Expression<Func<PlayersEntity, bool>> expression = Expression.Lambda<Func<PlayersEntity, bool>>(condtion, param ); 
       //后面的两个参数是用来分页的
       return (List<PlayersEntity>)_database.FindListByIndex(out int temp2, expression, null, 1, 5);
   }

数据库层

 public IEnumerable<T> FindListByIndex<T>(out int total,Expression<Func<T,bool>> filter =null,Func<IQueryable<T>,IOrderedQueryable<T>> orderBy =null,int index = 1,int size =20) where T : class
  {
      int skipCount = (index - 1) * size;
      var _reset = Find(filter, orderBy);
      total = _reset.Count();
      _reset = skipCount > 0 ? _reset.Skip(skipCount).Take(size) : _reset.Take(size);
      return _reset.ToList();
  }
     
private IQueryable<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null) where TEntity : class
   {
        IQueryable<TEntity> query = dbContext.Set<TEntity>();
        if (filter != null)
        {
            query = query.Where(filter);
        }
        if (orderBy != null)
        {
            return orderBy(query).AsQueryable();
        }
        else
        {
            return query.AsQueryable();
        }
    }
上一篇:python模块之re正则表达式


下一篇:《On Java 8》读书笔记012_集合