简体   繁体   English

Linq 查询具有父子关系中的多个对象

[英]Linq query with multiple objects in parent child relationship

I have a schema like this我有这样的架构

Package -> Lists -> Users Package -> 列表 -> 用户

All 'one to many' down the line...所有的“一对多”下线......

So I want to run a query where I get all packages that a userID matches in users.所以我想运行一个查询,在其中获取用户 ID 与用户匹配的所有包。

var pck = (from pk in context.Package
             where pk.Lists[here's my problem]

I would assume the navigation properties here would be: pk.Lists. *Users.UserId* == MyUserId我假设这里的导航属性是: pk.Lists. *Users.UserId* == MyUserId pk.Lists. *Users.UserId* == MyUserId , however I'm not seeing the navigation properties at the Lists level. pk.Lists. *Users.UserId* == MyUserId ,但是我没有在列表级别看到导航属性。

I haven't gotten to more complex EF queries like this yet.我还没有得到像这样更复杂的 EF 查询。 I've looked around the web but haven't found anything to make it click.我环顾四周 web 但没有找到任何让它点击的东西。 I turn to you stack.我转向你堆栈。 Somebody help me see the light!谁来帮我看看光明!

EDIT: Thanks again stack, I will do my best to pay it forward, Also, all of these answers enlightened me to the power of ef4!编辑:再次感谢堆栈,我会尽力向前支付,此外,所有这些答案都让我了解了 ef4 的力量!

I assume that a package contains multiple lists, and a list contains multiple users?我假设一个 package 包含多个列表,一个列表包含多个用户? You could try:你可以试试:

var pck = content.Package
     // Outdented just for Stack Overflow's width
     .Where(pk => pk.Lists.Any(list => list.Any(u => u.UserId == myUserId)));

Or use a cross-join:或者使用交叉连接:

var pck = from pk in content.Package
          from list in pk.Lists
          from user in list.Users
          where user.UserId == myUserId
          select ...; // Select whatever you're interested in

try this:尝试这个:

pk.Lists.Any(l => l.Users.Any(u => u.UserId == MyUserId))
context.Packages.Where(p => p.Lists.Any(l => l.Users.Contains(MyUserId)))

or, if your user is something other then just a user id,或者,如果您的用户是其他用户,则只是用户 ID,

context.Packages.Where(p => p.Lists.Any(l => l.Users.Any(u => u.Id == MyUserId)))
var packages =
    context.Package.Where(p =>
        p.Lists.Any(l => 
            l.Users.Any(u => u.UserId == MyUserId
        )
    );

If the links are non-nullable and direction is package has many lists and list has many users, then the query is pretty easy.如果链接不可为空并且方向是 package 有很多列表并且列表有很多用户,那么查询很容易。

var pck = from user in context.Users
          where user.UserId == userId
          select user.List.Package;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM