开发者

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

开发者 https://www.devze.com 2023-01-26 07:16 出处:网络
I have two entities, Ac开发者_开发知识库count 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 have two entities, Ac开发者_开发知识库count 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?


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:

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

And EF creates the association in the model:

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

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

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


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?
  } 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消