EF:当我定义具有相同签名的委托时,OrderBy不起作用

时间:2016-11-10 16:24:16

标签: entity-framework linq

我已经用ObjectDataSource替换了一个SqlDataSource。这是我的Select方法的一部分

Func<User, string> sortByDlg = (u) =>
{
  string sortStr = string.IsNullOrEmpty(sortColumn) ? "UserName" : sortColumn;
  return sortStr;
};

var users = db.Users.OrderBy(sortByDlg).ToList();

第一次加载页面时,我想要按 UserName 对行进行排序,然后按所选列进行排序。

当我运行代码时,没有发生排序。它仅在我放回匿名方法时才有效:OrderBy(u => u.UserName)

这是完整的方法

public static List<UserViewModel> GetAllUserViewModels(string sortColumn)
{
  using (var db = myDbContext.Create())
  {
    var model = new List<UserViewModel>();
    Func<User, string> sortByDlg = (u) =>
    {
        string sortStr = string.IsNullOrEmpty(sortColumn) ? "UserName" : sortColumn;
          return sortStr;
    };

    var users = db.Users.OrderBy(sortByDlg).ToList();
    foreach (var item in users)
    {
        var u = new UserViewModel
        {
           UserID = item.Id,
           First_Name = item.FirstName,
           Last_Name = item.LastName,
           telephone = item.Telephone,
           //more here ...
         };

         model.Add(u);
       }
       return model;
     }
    }

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我就是这样做的,因为我发现它很容易理解(不使用表达式树):

public static List<UserViewModel> GetAllUserViewModels(string sortColumn)
{
  using (var db = myDbContext.Create())
  {
    var query = db.Users.AsQueryable();
    switch(string.IsNullOrEmpty(sortColumn) ? "UserName" : sortColumn)
    {
       case "UserName": query=query.OrderBy(u=>u.UserName); break;
       case "FirstName": query=query.OrderBy(u=>u.FirstName); break;
       ... more ...
    }
    var model = query.Select(u=> new UserViewModel {
           UserID = item.Id,
           First_Name = item.FirstName,
           Last_Name = item.LastName,
           telephone = item.Telephone,
           //more here ...
         }).ToList();
    return model;
  }
}

实际上,我会为GetAllUsers创建函数,返回IQueryable<User>,单独的扩展方法IQueryable<User> OrderByColumn(this IQueryable<User> u,string sortColumn)和另一个扩展IEnumerable<UserViewModelItem> ToViewModel(this IQueryable<User> u),并使用它们:var result = GetAllUsers().OrderByColumn("UserName").ToViewModel();

// db defined elsewhere (repository pattern?)    
public IQueryable<User> GetAllUsers()
{
    return db.Users.AsQueryable();
}

public static IQueryable<User> OrderByColumn(this IQueryable<User> u,string sortColumn)
{
    switch(string.IsNullOrEmpty(sortColumn) ? "UserName" : sortColumn)
    {
       case "UserName": return u.OrderBy(u=>u.UserName); break;
       case "FirstName": return u.OrderBy(u=>u.FirstName); break;
       ... more ...
    }
}

public static IEnumerable<UserViewModelItem> ToViewModel(this IQueryable<User> users)
{
    return users.Select(u=> new UserViewModelItem {
           UserID = item.Id,
           First_Name = item.FirstName,
           Last_Name = item.LastName,
           telephone = item.Telephone,
           //more here ...
         }).ToList();
}