gpt4 book ai didi

linq - 用于排序导航属性的动态 LINQ 表达式

转载 作者:行者123 更新时间:2023-12-04 15:47:17 26 4
gpt4 key购买 nike

MVC3, Entity Framework 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

}

排序的动态表达式(只是为了避免 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;
}

该页面使用 webgrid 显示一个包含两列 Program Name 和 University Name 的网格。 Program Name 列的排序工作正常,但是如果按大学名称排序则会失败,因为此属性在 UniversityMaster 中并且 Expression.PropertyOrField 在 ProgramMaster 中搜索此属性。这是异常(exception):

University.UniversityName' is not a member of type '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;
}

关于linq - 用于排序导航属性的动态 LINQ 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9431637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com