在本实现中,我们需要实体“Company”和“Corporate”。连接到数据库后,我使用LINQ to SQL设计器来创建实体对象。公司实体的主页是显示它所属的公司;所以在网格中我们将有这些列:
CompanyName | CorporateName |描述
公司表只有公司ID而不是公司名称;但LINQ可以加载公司对象并访问公司记录的名称。
由于为网格列启用了排序,因此用户可以单击列以按该列排序结果(DESC或ASC)
排序适用于 CompanyName 和说明,但不适用于* CorporateName * !
下面是排序网格数据的代码
var entityType = typeof(Entities.Company);
//load company list based on Business Unit selected
var companyList = LoadCompanyRecords());// return type IQueryable<Entities.Company>
//if filters are used -> filter the results
companyList = FilterResults(companyList);//return type is IQueryable<Entities.Company>
// order by work flow starts
const string ascSortMethodName = "OrderBy";
const string descSortMethodName = "OrderByDescending";
var sortMethod = ascSortMethodName;
var orderdirection = GetSortDirection(e.SortExpression);
if (orderdirection == "DESC")
sortMethod = descSortMethodName;
//var entityType = typeof(Entities.Company);
var property = entityType.GetProperty(e.SortExpression);
var parameter = Expression.Parameter(entityType, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(
typeof(Queryable),
sortMethod,
new Type[] { entityType, property.PropertyType },
companyList.Expression,
Expression.Quote(orderByExp));
var result = companyList.Provider.CreateQuery<Entities.Company>(resultExp);
gvAssets.DataSource = result;
gvAssets.DataBind();
以前有人遇到过这个吗?什么是处理排序不属于当前实体的列的最佳方法? 或者我应该考虑编写SQL连接查询还是可以是存储过程?
我感谢任何帮助。
答案 0 :(得分:1)
对此的临时解决方案是检查该列名称,并确保它具有自己的排序功能,如下所示:
var sortColumn = e.SortExpression;
if (sortColumn == "CorporateGroupName")
{
if (orderdirection == "DESC")
result = companyList.OrderByDescending(x => x.CorporateGroup.CorporateGroupName).ToList();
else
result = companyList.OrderBy(x => x.CorporateGroup.CorporateGroupName).ToList();
}