我的要求是在运行时根据列来命令表。所以我经历了参数表达的路径。当所有列都存在于单个表中时,我能够实现它。这是我的代码:
我的要求是在运行时根据buildStatusOrder
订购表格:
List<BuildStatusEnum> buildStatusOrder = new List<BuildStatusEnum>
{
BuildStatusEnum.h,
BuildStatusEnum.f,
BuildStatusEnum.a
};
ParameterExpression parameterExpression = Expression.Parameter(typeof(companyQueue));
MemberExpression memberExpression = Expression.PropertyOrField(parameterExpression, "buildStatusID");
MemberExpression valueExpression = Expression.Property(memberExpression, "Value");
Expression orderByExpression = Expression.Constant(buildStatusOrder.Count);
for (int statusIndex = buildStatusOrder.Count - 1; statusIndex >= 0; statusIndex--)
{
ConstantExpression constantExpression = Expression.Constant((int)buildStatusOrder[statusIndex]);
ConstantExpression indexConstantExpression = Expression.Constant(statusIndex);
BinaryExpression equalExpression = Expression.Equal(valueExpression, constantExpression);
orderByExpression = Expression.Condition(equalExpression, indexConstantExpression, orderByExpression);
}
MemberExpression hasValueExpression = Expression.Property(memberExpression, "HasValue");
ConditionalExpression nullCheckExpression = Expression.Condition(hasValueExpression, orderByExpression, Expression.Constant(buildStatusOrder.Count));
var orderByLambda = Expression.Lambda<Func<companyQueue, int>>(nullCheckExpression, parameterExpression);
using (KapowContext context = new KapowContext())
{
var queue = context.companyQueues
.Where(cq => cq.u.s.cq.userID == Utilities.Authentication.UserId)
.Where(cq => buildStatusOrder.Contains((BuildStatusEnum)cq.u.s.cq.buildStatusID))
.OrderBy(o => o.u.se.segmentId)
.ThenBy(orderByLambda)
这很好用。我必须显示一个额外的列。它来自另一张桌子。所以我加入了桌子。我的lambda表达式现在看起来像这样:
var queue = context.companyQueues
.Join(context.abcd, cq => cq.robotID, r => r.robotId, (cq, r) => new { cq, r })
.Join(context.efgh, s => s.r.segmentId, se => se.segmentId, (s, se) => new { s, se })
.Join(context.hijk, u => u.s.cq.userID, us => us.userID, (u, us) => new { u, us })
.Where(cq => cq.u.s.cq.userID == Utilities.Authentication.UserId)
.Where(cq => buildStatusOrder.Contains((BuildStatusEnum)cq.u.s.cq.buildStatusID))
.OrderBy(orderByLambda)
现在我的orderbyLambda
无效了。我收到以下错误:
&#39;
System.Linq.Queryable.ThenBy<TSource,TKey>(System.Linq.IOrderedQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,TKey>>)
&#39;无法从使用中推断出来。尝试显式指定类型参数。