如何从List 中选择List ,其中A和B是使用Entity Framework相关的多对多关系?

时间:2022-09-02 20:17:30

I have 2 models, say Product and Category:

我有2个型号,比如产品和类别:

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?

我只想选择其标题包含关键字的产品类别。我做得对吗?

2 个解决方案

#1


1  

something like:

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

should do.

#2


1  

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:

我宁愿从类别开始,并在其相关产品上应用任何基于条件。这样查询就不需要对可能成本高昂的结果应用Distinct:

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

#1


1  

something like:

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

should do.

#2


1  

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:

我宁愿从类别开始,并在其相关产品上应用任何基于条件。这样查询就不需要对可能成本高昂的结果应用Distinct:

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