我正在使用.net core和EF core 2.0。 我有以下3张桌子
现在我想在有2列的屏幕上显示数据 1.用户名 2.角色
为了允许用户排序,搜索和分页,我在应用程序中遵循了通用代码。
public async Task<PagedResult<User>> GetAll(string filter, int pageIndex, int pageSize, string sortColumn, string sortDirection)
{
filter = filter?.Trim().ToLower();
var data = usersRepository.Query(true).Include(x => x.UserRoles).ThenInclude(x => x.Role).AsQueryable();
try
{
if (!string.IsNullOrWhiteSpace(filter))
{
data = data.Where(x => x.Username.ToLower().Contains(filter));
}
//sort
var ascending = sortDirection == "asc";
if (!string.IsNullOrWhiteSpace(sortColumn))
{
switch (sortColumn.Trim().ToLower())
{
case "username":
data = data.OrderBy(p => p.Username, ascending);
break;
case "isactive":
data = data.OrderBy(p => p.IsActive, ascending);
break;
case "role":
data = data.OrderBy(p => p.UserRoles.OrderBy(o => o.Role.Name), ascending);
break;
default:
data = data.OrderBy(p => p.Username, ascending);
break;
}
}
var test = data.ToList();
}
catch (Exception e)
{
//todo:
}
return await data.GetPaged(pageIndex, pageSize);
}
OrderBy是通用方法
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool ascending)
{
return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector);
}
现在,除了我通过搜索列“ role”时,其他所有方法都工作正常。
它给了我以下错误。
异常:无法比较数组中的两个元素。
InnerException :至少一个对象必须实现IComparable。
我将如何处理这种情况,我们将不胜感激。
答案 0 :(得分:0)
使用中间层来管理角色名称列。为此,我在响应中创建了一个名为“ UserList” 的新类,其中包含必需的属性。
public async Task<PagedResult<UserList>> GetAll(string filter, int pageIndex, int pageSize, string sortColumn, string sortDirection)
{
filter = filter?.Trim().ToLower();
var data = usersRepository.Query(true)
.Include(x => x.UserRoles)
.ThenInclude(x => x.Role)
.Select(x => new UserList()
{
Username = x.Username,
UserId = x.UserId,
IsActive = x.IsActive,
RoleId = x.UserRoles.FirstOrDefault().RoleId,
RoleName = x.UserRoles.FirstOrDefault().Role.Name
})
.AsQueryable();
try
{
if (!string.IsNullOrWhiteSpace(filter))
{
data = data.Where(x => x.Username.ToLower().Contains(filter) || x.RoleName.ToLower().Contains(filter));
}
//sort
var ascending = sortDirection == "asc";
if (!string.IsNullOrWhiteSpace(sortColumn))
{
switch (sortColumn.Trim().ToLower())
{
case "username":
data = data.OrderBy(p => p.Username, ascending);
break;
case "isactive":
data = data.OrderBy(p => p.IsActive, ascending);
break;
case "rolename":
data = data.OrderBy(p => p.RoleName, ascending);
break;
default:
data = data.OrderBy(p => p.Username, ascending);
break;
}
}
}
catch (Exception e)
{
//todo:
}
return await data.GetPaged(pageIndex, pageSize);
}