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


i'm starting use linqkit entityframework 6.0.2 , have following question...

why 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 cast object of type          'system.linq.expressions.fieldexpression' 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 expression accessing field. exception tells you accessing field.

the expression not evaluated when create query. executed once execute it. @ point, need resolve field. workaround getting expression first 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 using entityframework, happen expression converted sql query. however, since accessing class inside expression, cannot convert sql statement (how that?). when have instance of expression (with local variable) eliminating class access , expression can converted sql.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -