相关疑难解决方法(0)

按字符串生成EF orderby Expression

我想通过字符串参数生成表达式,一些代码如:

private Expression<Func<Task, T>> Generate(string orderby)
{
    switch (orderby)
    {
        case "Time":  
            return t => t.Time;
        case "Money":
            return t => t.RewardMoney;
        default:
            return t => t.Id;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后叫它:

_context.Items.OrderBy(Generate("Money"));
Run Code Online (Sandbox Code Playgroud)

但它无法编译!我将T改为对象.

private Expression<Func<Task, object>> Generate(string orderby)
Run Code Online (Sandbox Code Playgroud)

然后它可以编译,但它不起作用.

System.NotSupportedException:无法将类型"System.Int32"强制转换为"System.Object"类型.LINQ to Entities仅支持转换EDM原语或枚举类型.

c# linq entity-framework expression-trees

15
推荐指数
3
解决办法
9864
查看次数

标签 统计

c# ×1

entity-framework ×1

expression-trees ×1

linq ×1