gpt4 book ai didi

entity-framework - 在 EF Code First Orderby 函数期间无法将类型 'System.Int32' 转换为类型“System.Object”

转载 作者:行者123 更新时间:2023-12-04 15:29:20 25 4
gpt4 key购买 nike

我在 EF Code First 中使用规范模式。当我按操作排序时,VS 抛出一个新异常

enter image description here

规范模式复制自 eShopOnWeb

我只是稍微改变一下,这是我的更改代码:

public class Specification<T> : ISpecification<T>
{

public Expression<Func<T, object>> OrderBy { get; private set; }

public Specification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}

public Specification<T> OrderByFunc(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
return this;
}
}

这是我的调用代码,非常简单:
static void TestSpec()
{
var spec = new Specification<ExcelData>(x => x.RowIndex == 5)
.OrderByFunc(x => x.ColumnIndex);

using (var dbContext = new TechDbContext())
{
var top10Data = dbContext.ExcelData.Take(10).ToList();
var listExcel = dbContext.ApplySpecification(spec).ToList();

Console.WriteLine();
}
}

如果我评论 OrderByFunc ,那么对我来说一切都很好。 vs. 没有错误抛出

我曾多次尝试在 google 中搜索错误消息,但没有一个答案是我的情况。

所以我必须在这里问一个问题。

当我调试时 订购方式 房产在 SpecificationEvaluator.cs ,我发现有一个 转换 方法。
enter image description here

所以我知道这个错误是关于转换错误的,但是我该如何解决这个转换类型错误呢?

请帮我!

最佳答案

解决方案是创建新的 lambda 表达式并移除 cast ( Convert ),然后使用它来调用 Queryable类(class)OrderBy/OrderByDescending方法动态(使用 DLR 调度或反射)或通过发出 Expression.Call到它。

对于第一部分,将以下帮助方法添加到 SpecificationEvaluator类(class):

static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}

然后替换代码
query = query.OrderBy(specification.OrderBy);


query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));

或者
var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new[] { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));

specification.OrderByDescending 做类似的事情.

关于entity-framework - 在 EF Code First Orderby 函数期间无法将类型 'System.Int32' 转换为类型“System.Object”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985059/

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