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?
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
没有实体类结构,很难回答,但应该类似于:
var categories = context.Categories.Where(c => c.Items.Any(i => i.Tags.Any(t => t.Name == "myTagName"))).ToList();
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.