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

不打扰是莪最后的温柔 提交于 2019-12-08 07:08:42

问题


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?


回答1:


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:

And EF creates the association in the model:

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




回答2:


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


来源:https://stackoverflow.com/questions/4235978/using-linq-and-entity-how-do-i-return-values-of-a-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!