Linq query with multiple objects in parent child relationship
I have a schema like this
Package -> Lists -> Users
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.
var pck = (from pk in context.Package
whe开发者_Go百科re pk.Lists[here's my problem]
I would assume the navigation properties here would be: pk.Lists. *Users.UserId* == MyUserId
, however I'm not seeing the navigation properties at the Lists level.
I haven't gotten to more complex EF queries like this yet. I've looked around the web but haven't found anything to make it click. 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!
I assume that a package contains multiple lists, and a list contains multiple users? 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
context.Packages.Where(p => p.Lists.Any(l => l.Users.Contains(MyUserId)))
or, if your user is something other then just a user 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.
var pck = from user in context.Users
where user.UserId == userId
select user.List.Package;
try this:
pk.Lists.Any(l => l.Users.Any(u => u.UserId == MyUserId))
精彩评论