“参数表达式无效”与EF4 Linq子选择查询错误 [英] "Argument expression is not valid" error with EF4 Linq sub select query

查看:173
本文介绍了“参数表达式无效”与EF4 Linq子选择查询错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何关于为什么这个查询编译但是抛出这个运行时错误的想法:

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();


推荐答案

我发现我有最好的运气与复杂使用let表达式进行内部查询。这样做是一个子选择,并允许您更灵活地从子选择中绑定元素。不过,请注意,我只是在匿名对象的作者作业中做一个First()。这是因为如果你做一个First()。PropertyName和First产生一个空值,它将会爆炸。

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.

var books = (
        from b in db.BOOKs
        let author = (from a in db.PEOPLEs
                      where b.AUTHOR == a.ID
                      select a)
        select new
        {
            ID = b.ID,
            NAME = b.Name,
            Author = author.First()
        }
    ).ToList();    

foreach(var x in books)
{
    string AuthorName = x.Author.USER_ID;
    //Do other stuff
}

这篇关于“参数表达式无效”与EF4 Linq子选择查询错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆