Why am I getting an InvalidCastException when using an expression from a static field?

别说谁变了你拦得住时间么 提交于 2019-12-04 10:10:23

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

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;
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!