user427875
user427875

Reputation: 1265

Using LINQ and Entity how do I return values of a many-to-many relationship

I have two entities, Account and Subscription with a many-to-many association between them. I can't seem to find in the tutorials anywhere how to do the following:

I want to find all the Accounts with a Subscription of type x. If I wasn't using the Entity framework I could join to the AccountSubscription table, but that isn't accessible via Entity. Do I have to create a special entity if I need to query on a many-to-many relationship?

Upvotes: 1

Views: 455

Answers (2)

Jeff Ogata
Jeff Ogata

Reputation: 57783

EF should create a navigation property for a many-to-many relationship. Then you should be able to do something like this:

var accounts = from a in Accounts
               where a.Subscriptions.Any(s => s.SubscriptionType == "something")
               select a;

For example, I have a simple db with a many to many relationship between Products and Groups: alt text

And EF creates the association in the model: alt text

So I can create a query like this (here including the Groups so I can see the Category):

alt text

Upvotes: 3

Abe Miessler
Abe Miessler

Reputation: 85056

What about something like this:

List<Accounts> myAccounts = //get accounts;

foreach(Accounts a in myAccounts)
{
  foreach(Subscriptions s in a)
  {
     //add it to a global list?
  } 
}

Upvotes: 0

Related Questions