1

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
             where 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!

5 Answers 5

8

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
Sign up to request clarification or add additional context in comments.

Comments

1
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)))

1 Comment

I'm starting to see the light!
1
var packages =
    context.Package.Where(p =>
        p.Lists.Any(l => 
            l.Users.Any(u => u.UserId == MyUserId
        )
    );

Comments

1

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;

1 Comment

this select technique helped me weeks after I asked the question! This page has been a great reference for me! Really opening my eyes to the ease of EF!
1

try this:

pk.Lists.Any(l => l.Users.Any(u => u.UserId == MyUserId))

1 Comment

That does make perfect sense, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.