“参数表达式无效” EF4 Linq 子选择查询出错
关于为什么此查询编译但随后抛出此运行时错误的任何想法:
参数表达式无效
我知道我可以更改我的数据库模型,但在这种情况下这是不可能的。 有什么想法如何让这样的事情发挥作用吗?甚至不确定这会被称为什么。谢谢。
DBContext db = new DBContext();
var books = (from b in db.BOOKS
select new
{
b.ID,
b.NAME,
AuthorName = db.PEOPLEs.Where(p=>p.ID==b.AUTHOR).First().USER_ID,
}).ToList();
Any ideas as to why this query compiles, but then throws this runtime error:
Argument expression is not valid
I know I could change my db model, but in this case it's not possible.
Any ideas how to get something like this working? Not even sure what this would be called. Thanks.
DBContext db = new DBContext();
var books = (from b in db.BOOKS
select new
{
b.ID,
b.NAME,
AuthorName = db.PEOPLEs.Where(p=>p.ID==b.AUTHOR).First().USER_ID,
}).ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现通过使用 let 表达式,我在复杂的内部查询方面运气最好。这会执行子选择,并允许您更灵活地绑定子选择中的元素。但是,请注意,我仅对匿名对象中的作者分配执行 First() 。这是因为如果你执行 First().PropertyName 并且 First 产生一个 null 值,它就会爆炸。
祝你好运并仔细检查语法。我没有完整的对象集,因此我无法生成完全工作的演示,但是,这是使用我自己的项目之一的对象树进行测试的。
I've found I have the best luck with complex inner queries by using let expressions. This does a subselect and allows you greater flexibility to bind an element from a subselect. HOWEVER, notice that I am only doing a First() on the author assignment in the anonymous object. This is because if you do a First().PropertyName and First yields a null value it will blow up.
Good luck and double check syntax. I don't have your full object set so I cannot generate a fully working demo, however, this was tested with an object tree that I have on one of my own projects.
如果你看一下你的代码,你会
发现它需要另一个参数,只需删除它,它就会通过
:)
If you have a look on your code, you have
It is expecting another parameter there, just remove it and it sould pass
:)
所以,最终的解决方案是:
谢谢!
So, the final solution was:
Thanks!
无论如何,
First()
也有一个重载First(Predicate)
,即:您可以在方法样式中使用 LINQ:
Anyway,
First<T>()
also have an overloadFirst<T>(Predicate<T>)
, i.e.:You can use LINQ in methods styles: