[英]Why am I getting an InvalidCastException when using an expression from a static field?
I'm just starting to use LinqKit with EntityFramework 6.0.2 and I have the following question... 我刚刚开始使用LinqKit和EntityFramework 6.0.2,我有以下问题......
Why does this: 为什么这样:
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;
}
throw: 扔:
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'.
but this: 但是这个:
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;
}
works fine? 工作良好?
That's because inside your expression you are accessing a Field. 那是因为在你的表达中你正在访问一个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. 看到您在EntityFramework中使用它,会发生什么是您的表达式将转换为SQL查询。 However, since you are accessing a class inside the expression, it cannot convert this to a SQL statement (how would it do that?).
但是,由于您正在访问表达式中的类,因此无法将其转换为SQL语句(它将如何执行此操作?)。 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.
当你有一个表达式的实例(使用局部变量)时,你将消除这个类访问,并且该表达式可以转换为SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.