为什么我会收到一个InvalidCastException从静态字段使用EX pression什么时候? [英] Why am I getting an InvalidCastException when using an expression from a static field?

查看:119
本文介绍了为什么我会收到一个InvalidCastException从静态字段使用EX pression什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 LinqKit ,提供的EntityFramework 6.0.2和我有以下问题...

I'm just starting to use LinqKit with EntityFramework 6.0.2 and I have the following question...

为什么这样的:

public static readonly Expression<Func<MyEnum, string>> ConvertToString = e => 
        e == MyEnum.One
                    ? "one"
                    : e == MyEnum.Two
                        ? "two"
                        : "zero";

private static string GetSomethingElse(IQueryable<EnumTest> things)
{           
    var ret = things
        .AsExpandable()
        .Select(c => Program.ConvertToString.Invoke(c.SomeEnum))
        .First();
    return ret;
}

投掷:

An unhandled exception of type 'System.InvalidCastException' 
    occurred in LinqKit.dll

Additional information: Unable to cast object of type     
    'System.Linq.Expressions.FieldExpression' to type 
    'System.Linq.Expressions.LambdaExpression'.

但这样的:

private static string GetSomething(IQueryable<EnumTest> things)
{
    Expression<Func<MyEnum, string>> ConvertToString = e => e == MyEnum.One
        ? "one"
        : e == MyEnum.Two
            ? "two"
            : "zero";

    var ret = things
        .AsExpandable()
        .Select(c => ConvertToString.Invoke(c.SomeEnum))
        .First();
    return ret;
}

工作正常?

推荐答案

这是因为,在你的前pression您正在访问现场。例外情况告诉你,你正在访问一个字段。

That's because inside your expression you are accessing a Field. The exception tells you that you are accessing a field.

在创建查询的EX pression不评估。它只能执行一次执行它。在这一点上,它需要解决的领域。一种解决方法是先取前pression到一个局部变量:

The expression is not evaluated when you create the query. It is only executed once you execute it. At that point, it will need to resolve the field. A workaround is getting the expression first into a local variable:

private static string GetSomething(IQueryable<EnumTest> things)
{
    var expression = Program.ConvertToString;

    var ret = things
        .AsExpandable()
        .Select(c => expression.Invoke(c.SomeEnum))
        .First();
    return ret;
}

看到您正在使用该用的EntityFramework,会发生什么事是你的前妻pression将被转换为SQL查询。但是,因为你正在访问里面的前pression一类,它不能转换为SQL语句(会是怎样做到这一点?)。 当你有前pression的实例(与本地变量)您已消除这种类的访问,并且前pression可以转换到SQL

Seeing that you are using this with EntityFramework, what will happen is that your expression will be converted to a SQL query. However, since you are accessing a class inside the expression, it cannot convert this to a SQL statement (how would it do that?). When you have an instance of the expression (with the local variable) you are eliminating this class access and that expression can be converted into SQL.

这篇关于为什么我会收到一个InvalidCastException从静态字段使用EX pression什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆