John
John

Reputation: 1922

DBContext and Navigational Properties

OK I am stuck. I have a model that has a "USER" entity, a "CLUB" entity, and a "MEMBERSHIP" entity. The "MEMBERSHIP" entity is the association of "USER" to "CLUB". A user can have many clubs and a club can have many users.

I cant figure out how to get a list of clubs for a particular user.

I just cant find a good example on how to build this query.

I seem to be having a problem because the navigational property is a collection.

Can anyone point me in the right direction, thanks.

Upvotes: 0

Views: 60

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

It depends on Membership table. If table is just simple association, which has UserId and ClubId, then Membership entity will not be generated, and you should query this way:

var clubs = context.Users
                   .Where(u => u.Id == id)
                   .SelectMany(u => u.Clubs);

If association is not that simple, then Membership entity will be generated, and you should navigate to clubs via memberships, like this:

var clubs = context.Users
                   .Where(u => u.Id == id)
                   .SelectMany(u => u.Memberships)
                   .Select(m => m.Club);

Upvotes: 1

Related Questions