Ami*_*tdh 6 linq entity asp.net-mvc-3
MVC3,实体框架4.1代码优先.
使用2个表
模型:
public class UniversityMaster
{
[Key]
public string UniversityId { get; set; }
public string UniversityName { get; set; }
}
public class ProgramMaster
{
[Key]
public string ProgramId { get; set; }
public string ProgramName { get; set; }
public string UniversityId { get; set; }
public virtual UniversityMaster University { get; set; } // navigation property
}
Run Code Online (Sandbox Code Playgroud)
用于排序的动态表达式(仅用于避免switch case语句):
public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField="", string sortDirection="")
{
IQueryable<ProgramMaster> query = _dbSet;
ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
MemberExpression property = Expression.PropertyOrField(pe, sortField);
//get a exception here if the sort field is of navigation property (University.UniversityName)
LambdaExpression lambda = Expression.Lambda(property, pe);
if (sortDirection == "ASC")
orderbydir = "OrderBy";
else
orderbydir = "OrderByDescending";
MethodCallExpression call = Expression.Call(typeof(Queryable),
orderbydir, new Type[] { typeof(TEntity), property.Type }, query.Expression, Expression.Quote(lambda));
var returnquery = (IOrderedQueryable<ProgramMaster>)query.Provider.CreateQuery< ProgramMaster >(call);
return returnquery;
}
Run Code Online (Sandbox Code Playgroud)
该页面使用webgrid显示一个包含两列Program Name和University Name的网格."程序名称"列的排序工作正常,但如果按大学名称排序则会失败,因为此属性位于UniversityMaster中,而Expression.PropertyOrField会在ProgramMaster中搜索此属性.这是一个例外:
University.UniversityName'不是'App.Core.Model.ProgramMaster类型的成员
我的问题是我如何使我的模型类的导航属性.
希望我能够解释这个场景.任何帮助表示赞赏.
那是因为正在尝试调用参数上MemberExpression指定的成员。Univerty.UniversityName您想要做的是调用Univerity参数上命名的成员,然后调用UniversityName该成员。实际上,您需要迭代地解析属性名称。
public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField = "", string sortDirection = "")
{
IQueryable<ProgramMaster> query = _dbSet;
var propertyNames = sortField.Split(".");
ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
Expression property = pe;
foreach(var prop in propertyName)
{
property = Expression.PropertyOrField(property, prop);
}
LambdaExpression lambda = Expression.Lambda(property, pe);
if (sortDirection == "ASC")
orderbydir = "OrderBy";
else
orderbydir = "OrderByDescending";
MethodCallExpression call = Expression.Call(
typeof(Queryable),
orderbydir,
new Type[] { typeof(TEntity), property.Type },
query.Expression,
Expression.Quote(lambda));
var returnquery = (IOrderedQueryable<ProgramMaster>)query.Provider.CreateQuery<ProgramMaster>(call);
return returnquery;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1430 次 |
| 最近记录: |