EntityFrameworkCore DbSet.Where

时间:2017-06-28 02:39:43

标签: lambda entity-framework-core dbset

我想通过多个Lambda表达式过滤我的DbSet 这是实施。 1.Expression

public static Expression<Func<T, bool>> True<T>() { return f => true; }


public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
    var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
    return Expression.Lambda<Func<T, bool>>
    (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}      

2。实施CODE

public IEnumerable<ApplicationUser> GetMany(Expression<Func<ApplicationUser, bool>> where, int page, int pageSize, out int totalCount)
{
    totalCount = _userRepository.DbSet.Where(where).Count();
    var devices = _userRepository.DbSet.Where(where).Include(p => p.Group)
        .Skip((page - 1) * pageSize).Take(pageSize).AsEnumerable();
    return devices;
}

3.Controller

public async Task<IActionResult> GetAll([FromQuery] string name = "",int groupId=0, int page = 1, int pageSize = 20)
{
    int groupid = await GetCurrentLoginUserGroupID();
    List<int> _groupIdList = _groupSvc.GetGroupTreeID(groupid);
    IEnumerable<ApplicationUser> users = null;
    int totalCount = 0;
    if (pageSize >= ConstConfig.MaxItemSizePerPage)
    {
        pageSize = ConstConfig.MaxItemSizePerPage;
    }
    else if (pageSize < 1)
    {
        pageSize = 1;
    }            
    var where = PredicateBuilder.True<ApplicationUser>().And(g => _groupIdList.Contains(g.GroupId.GetValueOrDefault()));
    if (!string.IsNullOrEmpty(name))
    {
        where.And(n => n.UserName.Contains(name));
    }
    if (groupId > 0)
    {
        where.And(g => g.GroupId == groupId);
    }
    users = _userService.GetMany(where,page,pageSize, out totalCount);

我检查了name的值,但users的返回值不符合此过滤器 任何帮助将不胜感激。

0 个答案:

没有答案