如何选择列表< B>从列表< A>其中A和B是多对多使用实体框架?
问题描述:
我有两种型号,例如产品
和类别
:
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?
答
如下:
var p = db.Products.
Where(i => i.Title.Contains("Apple")).
SelectMany(i => i.Categories).
Distinct();
应该做。