标签:reset condtion int value 查询 EFCore null 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();
}
}
标签:reset,condtion,int,value,查询,EFCore,null,Expression 来源: https://blog.csdn.net/weixin_43519799/article/details/112800286
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。