如何选择列表< B>从列表< A>其中A和B是多对多使用实体框架? [英] How to select List<B> from List<A> where A and B are many-to-many related using Entity Framework?

查看:119
本文介绍了如何选择列表< 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();

应该做。

这篇关于如何选择列表&lt; B&gt;从列表&lt; A&gt;其中A和B是多对多使用实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆