Ron83
Ron83

Reputation: 92

Linq query with 2 many to many relations

I'm having a problem writing a Linq query that involves 2 many to many relations. I have following entities: Item - Tag - Category Item has a many to many with Tag Category has a many to many with Tag

The structure of my entities is as follows (I used a db first approach)
- Category(CategoryId, CategoryName, ICollection of Tag)
- Tag(TagId, TagName)
- Item(ItemId, ItemName, ICollection of Tag)

I want to get the list of items per category

Any idea how to realize this?

Upvotes: 0

Views: 101

Answers (3)

Ethan Li
Ethan Li

Reputation: 1001

var itemPerCategories = 
        db.Category.ToDictionary(
            c => c.CategoryName,
            c => c.Tags.SelectMany(t => t.Items)).ToList())
        );

itemPerCategories is a dictionary, which's key is the name of a category, and value are a list of all items in the category

Upvotes: 1

Ron83
Ron83

Reputation: 92

Found the answer:
var items = from c in db.Category
from t in c.Tag
from i in t.Item
where c.CategoryName == "categoryname"
select i;

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

It's a bit hard to answer without entity classes structure, but should be something like:

var categories = context.Categories.Where(c => c.Items.Any(i => i.Tags.Any(t => t.Name == "myTagName"))).ToList();

Upvotes: 0

Related Questions