如何向OrderBy传递字符串参数(Entity Framework)
Entity Framework提供的排序功能
再来回顾一下上篇文章,加载用户列表并进行排序数据库分页的代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
var q = DB.Users.Include(u => u.Dept); // 在用户名称中搜索string searchText = ttbSearchMessage.Text.Trim();if (!String.IsNullOrEmpty(searchText)){ q = q.Where(u => u.Name.Contains(searchText) || u.ChineseName.Contains(searchText) || u.EnglishName.Contains(searchText));} // 过滤启用状态if (rblEnableStatus.SelectedValue != "all"){ q = q.Where(u => u.Enabled == (rblEnableStatus.SelectedValue == "enabled" ? true : false));} // 在查询添加之后,排序和分页之前获取总记录数Grid1.RecordCount = q.Count(); // 排列q = q.OrderBy(u => u.Name); // 数据库分页q = q.Skip(Grid1.PageIndex * Grid1.PageSize).Take(Grid1.PageSize); Grid1.DataSource = q;Grid1.DataBind(); |
让我们把关注点集中到排序代码上:
|
1
|
q = q.OrderBy(u => u.Name); |
在FineUI实际应用中,我们一般是从表格的 SortField 中读取排序字段,显然EF提供的OrderBy无法接受字符串表示的排序字段。
手工创建Lamba表达式
通过搜索发现了这个帖子:http://stackoverflow.com/questions/10072250/generic-funct-k-to-sort-collections-of-different-types/10074873
据此我们可以写出如下的代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public Expression<Func<T, To>> GetSortExpression<T, To>(String sortBy){ var param = Expression.Parameter(typeof(T), "x"); Expression expr = Expression.Property(param, sortBy); return Expression.Lambda<Func<T, To>>(expr, param);} protected IQueryable<T> Sort<T>(IQueryable<T> q, FineUI.Grid grid){ string sortField = grid.SortField; if (grid.SortDirection == "ASC") { q = q.OrderBy(GetSortExpression<T, object>(sortField)); } else { q = q.OrderByDescending(GetSortExpression<T, object>(sortField)); } return q;} |
经过测试,我们发现这个方法不支持bool, int, DateTime, DateTime?类型的列排序。
经过扩展后的代码如下所示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
protected IQueryable<T> Sort<T>(IQueryable<T> q, FineUI.Grid grid){ string sortField = grid.SortField; var propertyType = typeof(T).GetProperty(sortField).PropertyType; if (grid.SortDirection == "ASC") { if (propertyType == typeof(bool)) { q = q.OrderBy(GetSortExpression<T, bool>(sortField)); } else if (propertyType == typeof(int)) { q = q.OrderBy(GetSortExpression<T, int>(sortField)); } else if (propertyType == typeof(DateTime)) { q = q.OrderBy(GetSortExpression<T, DateTime>(sortField)); } else if (propertyType == typeof(DateTime?)) { q = q.OrderBy(GetSortExpression<T, DateTime?>(sortField)); } else { q = q.OrderBy(GetSortExpression<T, object>(sortField)); } } else { if (propertyType == typeof(bool)) { q = q.OrderByDescending(GetSortExpression<T, bool>(sortField)); } else if (propertyType == typeof(int)) { q = q.OrderByDescending(GetSortExpression<T, int>(sortField)); } else if (propertyType == typeof(DateTime)) { q = q.OrderByDescending(GetSortExpression<T, DateTime>(sortField)); } else if (propertyType == typeof(DateTime?)) { q = q.OrderByDescending(GetSortExpression<T, DateTime?>(sortField)); } else { q = q.OrderByDescending(GetSortExpression<T, object>(sortField)); } } return q;} |
但这种做法过于臃肿,有没有更好的办法呢?
更好的SortBy扩展方法
后来,我们发现了这篇文章:http://stackoverflow.com/questions/3945645/sorting-gridview-with-entity-framework
通过对 IQueryable<T> 进行扩展,提供了接受类似 "Name DESC", "CreateTime", "CreateTime DESC" 参数的 SortBy 方法,更具有通用性。
原始的SortBy扩展方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public static class QueryExtensions { public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName) { if (source == null) { throw new ArgumentNullException("source"); } // DataSource control passes the sort parameter with a direction // if the direction is descending int descIndex = propertyName.IndexOf(" DESC"); if (descIndex >= 0) { propertyName = propertyName.Substring(0, descIndex).Trim(); } if (String.IsNullOrEmpty(propertyName)) { return source; } ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty); MemberExpression property = Expression.Property(parameter, propertyName); LambdaExpression lambda = Expression.Lambda(property, parameter); string methodName = (descIndex < 0) ? "OrderBy" : "OrderByDescending"; Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { source.ElementType, property.Type }, source.Expression, Expression.Quote(lambda)); return source.Provider.CreateQuery<T>(methodCallExpression); }} |
不过这个方法不支持"Name ASC"形式的参数,所以我们进行了简单的修正,修正后的SortBy扩展方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
public static class QueryExtensions{ public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string sortExpression) { if (source == null) { throw new ArgumentNullException("source"); } string sortDirection = String.Empty; string propertyName = String.Empty; sortExpression = sortExpression.Trim(); int spaceIndex = sortExpression.Trim().IndexOf(" "); if (spaceIndex < 0) { propertyName = sortExpression; sortDirection = "ASC"; } else { propertyName = sortExpression.Substring(0, spaceIndex); sortDirection = sortExpression.Substring(spaceIndex + 1).Trim(); } if (String.IsNullOrEmpty(propertyName)) { return source; } ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty); MemberExpression property = Expression.Property(parameter, propertyName); LambdaExpression lambda = Expression.Lambda(property, parameter); string methodName = (sortDirection == "ASC") ? "OrderBy" : "OrderByDescending"; Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { source.ElementType, property.Type }, source.Expression, Expression.Quote(lambda)); return source.Provider.CreateQuery<T>(methodCallExpression); } } |
优化后的排序分页代码
首先在页面基类PageBase中定义排序和分页的代码(使用了前面定义的 SortBy 扩展函数):
|
1
2
3
4
5
6
7
8
9
|
protected IQueryable<T> Sort<T>(IQueryable<T> q, FineUI.Grid grid){ return q.SortBy(grid.SortField + " " + grid.SortDirection);} protected IQueryable<T> SortAndPage<T>(IQueryable<T> q, FineUI.Grid grid){ return Sort(q, grid).Skip(grid.PageIndex * grid.PageSize).Take(grid.PageSize);} |
最终查询用户列表的代码:
var q = DB.Users.Include(u => u.Dept); // 在用户名称中搜索string searchText = ttbSearchMessage.Text.Trim();if (!String.IsNullOrEmpty(searchText)){ q = q.Where(u => u.Name.Contains(searchText) || u.ChineseName.Contains(searchText) || u.EnglishName.Contains(searchText));} // 过滤启用状态if (rblEnableStatus.SelectedValue != "all"){ q = q.Where(u => u.Enabled == (rblEnableStatus.SelectedValue == "enabled" ? true : false));} // 在查询添加之后,排序和分页之前获取总记录数Grid1.RecordCount = q.Count(); // 排列和数据库分页q = SortAndPage<User>(q, Grid1); Grid1.DataSource = q;Grid1.DataBind(); |
本博客空间内的文章均为转载,供大家学习、交流使用,如有侵权,请及时通知

浙公网安备 33010602011771号