How to select List<B> from List<A> where A and B are many-to-many related using Entity Framework?

雨燕双飞 提交于 2019-12-13 07:43:04

问题


I have 2 models, say Product and Category:

public class Category
{
    public Category() { }

    // primary key
    public long Id { get; set; }

    // other properties are omitted 

    public virtual IList<Product> Products { get; set; }
}


public class Product
{
    public Product() { }

    // primary key        
    public long Id { get; set; }

    // title/name
    public string Title { get; set; }

    public virtual IList<Category> Categories { get; set; }
}

As you can see there is a many-to-many relationship between these models; each product can have multiple categories and for each category we can have multiple products.

The question is how can I select distinct categories associated with a list of products. I want something like this:

// making a list of products
var p = db.Products.Where(i => i.Title.Contains("Apple"));

// getting distinct categories of those products
var c = p.Select(i => i.Categories)... // stuck here

I just want to select categories of the products that their title contains a keyword. Am I doing it right at all?


回答1:


something like:

var p = db.Products.
    Where(i => i.Title.Contains("Apple")).
    SelectMany(i => i.Categories).
    Distinct();

should do.




回答2:


I would rather start from Categories and apply Any based condition on their associated Products. This way the query will not need to apply Distinct on the result which might be costly:

var categories = db.Categories
    .Where(c => c.Products.Any(p => p.Title.Contains("Apple")));


来源:https://stackoverflow.com/questions/44782360/how-to-select-listb-from-lista-where-a-and-b-are-many-to-many-related-using

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