表达式树不能包含动态操作
如果我尝试将动态类型值传递到实体框架 linq 查询中,则会收到此错误。
dynamic sname = "suraj"; // even object, var
AppUser appUser = Ctx.AppUsers.First(u => u.Name == sname);
如果我尝试首先将值存储在字符串中并使用它,我得到 “对象引用错误”。
var name = "suraj";
string sname = new string(((string)name).ToCharArray());
AppUser appUser = Ctx.AppUsers.First(u => u.Name == sname);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看 DLINQ 允许您执行以下操作:
请注意,查询中的表达式是可以在运行时动态构造的字符串。
该库有一些非常非常好的功能,包括到表达式树的隐式转换,您将能够顺利地将其集成到现有的表达式树中。
(当您回想起 2006 年左右编写的 DLINQ 时,它是相当令人惊奇的,并且仍然处于 C# 技术进步的前沿;下载包含在此处的 \LinqSamples\DynamicQuery 目录)
Have a look at DLINQ which allows you to do stuff like:
Note that expressions in the query are strings that could have been dynamically constructed at run-time.
The library has some very very nice goodies, including implicit conversion to Expression Trees, that you will be able to smoothly integrate into your existing expression tree.
(DLINQ is pretty amazing when you think off how it was writting around 2006 and still is right on the front of C# technological advancements; Download included in the \LinqSamples\DynamicQuery directory here)
与@Suraj的答案类似,因为
dynamic
在委托中显然没问题(Func
)而不是表达式
,那么您可以将委托转换为表达式 :Similar to @Suraj's answer, since
dynamic
is apparently okay in a delegate (Func
) but not anExpression
, then you can convert the delegate into an expression: