如何将表达式传递到实体框架 LINQ 查询 OrderBy 子句中



我有以下 LINQ 查询:

using (var context = new EUContext())
{
var tmp = context.Terms.Include(x => x.StudentCourses)
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId)
.OrderBy(x => x.AcademicYear)
.ThenBy(x=> x.TermRegistered == "Fall" ? 1 :
x.TermRegistered == "Spring" ? 2 : 3));
return tmp.ToList();
}

我正在尝试在 ThenBy 子句中移动 OrdyBy 以清理代码。我正在尝试使用如下表达式:

private static Expression<Func<string, int>> TermsOrder(string x)
{
return (x == "Fall" ? 1 :
x == "Spring" ? 2 : 3);
}

我的代码应该看起来像这样:

using (var context = new EUContext())
{
var tmp = context.Terms.Include(x => x.StudentCourses)
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId)
.OrderBy(x => x.AcademicYear)
.ThenBy(x=> TermsOrder(x.TermRegistered));
return tmp.ToList();
}

不幸的是,表达式不起作用,表达式正文中有一长条波浪线,并显示以下错误消息:

不能将类型"int"隐式转换为"System.Linq.Expressions.Expression>

我做错了什么?这是我第一次尝试使用表达式,我知道由于不完全理解表达式的工作原理,我错过了一些明显的东西。

谢谢

这并不像看起来那么简单。您需要组合Expression或构建Expression才能生成所需的内容,不幸的是,C# 在这方面没有包含很多帮助。

最简单的方法是使用扩展方法来LambdaExpression组合。它依赖于一些Expression扩展方法,用于在Expression中将一个Expression替换为另一个:

public static class ExpressionExt {
// Compose: f.Compose(g) => x => f(g(x))
/// <summary>
/// Composes two LambdaExpression into a new LambdaExpression: f.Compose(g) => x => f(g(x))
/// </summary>
/// <param name="fFn">The outer LambdaExpression.</param>
/// <param name="gFn">The inner LambdaExpression.</param>
/// <returns>LambdaExpression representing outer composed with inner</returns>
public static Expression<Func<T, TResult>> Compose<T, TIntermediate, TResult>(this Expression<Func<TIntermediate, TResult>> fFn, Expression<Func<T, TIntermediate>> gFn) =>
Expression.Lambda<Func<T, TResult>>(fFn.Body.Replace(fFn.Parameters[0], gFn.Body), gFn.Parameters[0]);    
/// <summary>
/// Replaces a sub-Expression with another Expression inside an Expression
/// </summary>
/// <param name="orig">The original Expression.</param>
/// <param name="from">The from Expression.</param>
/// <param name="to">The to Expression.</param>
/// <returns>Expression with all occurrences of from replaced with to</returns>
public static Expression Replace(this Expression orig, Expression from, Expression to) => new ReplaceVisitor(from, to).Visit(orig);
}
/// <summary>
/// Standard ExpressionVisitor to replace an Expression with another in an Expression.
/// </summary>
public class ReplaceVisitor : ExpressionVisitor {
readonly Expression from;
readonly Expression to;
public ReplaceVisitor(Expression from, Expression to) {
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node) => node == from ? to : base.Visit(node);
}

现在,您可以创建采用表示要测试的字段的 lambda 的方法。它使用本地LambdaExpression作为最终结果的模板:

public static class Util {
static Expression<Func<string, int>> TermOrderTemplateFn = p => (p == "Fall" ? 1 : p == "Spring" ? 2 : 3);
public static Expression<Func<TRec, int>> TermsOrder<TRec>(Expression<Func<TRec, string>> selectorFn) =>
TermOrderTemplateFn.Compose(selectorFn);
}

现在,您可以在表达式中调用该方法,传入表示所需字段(或字段表达式)的 lambda 进行测试:

var tmp = context.Terms.Include(x => x.StudentCourses).AsQueryable()
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId)
.OrderBy(x => x.AcademicYear)
.ThenBy(Util.TermsOrder<Term>(p => p.TermRegistered));

注意:我正在调用context.Terms.First()Term类型,但您需要在调用TermsOrder时使用实际正确的类型名称。您也可以改为TermsOrder((Term p) => ...)

我可能更愿意创建一个特殊版本的ThenBy,以便您可以使用类型推断来确定记录类型:

public static class EFExt {
static Expression<Func<string, int>> TermThenOrderTemplateFn = p => (p == "Fall" ? 1 : p == "Spring" ? 2 : 3);
public static IOrderedQueryable<T> ThenByTerm<T>(this IOrderedQueryable<T> src, Expression<Func<T, string>> selectorFn) =>
src.ThenBy(TermThenOrderTemplateFn.Compose(selectorFn));
}

然后你可以直接使用它:

var tmp = context.Terms.Include(x => x.StudentCourses).AsQueryable()
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId)
.OrderBy(x => x.AcademicYear)
.ThenByTerm(p => p.TermRegistered);

最新更新