【问题标题】:EF CodeFirst Linq Query Many to manyEF Code First Linq 查询多对多
【发布时间】:2013-11-25 12:22:32
【问题描述】:

我有两个类形成多对多关系。

public class Product
{
    public int ID { get; set; }
    public virtual ICollection<Category> Categories{ get; set; }
}

public class Category
{
    public int ID { get; set; }
    public virtual ICollection<Product> Products{ get; set; }
}

我需要选择包含在某个类别中的所有产品。例如 ID 为 1 的类别中的所有产品,或 ID 为 1 和 3 的类别中的所有产品。 如何在 Linq 中编写此查询?

注意: 我想用这个作为过滤技术。我有这个代码:

public IQueryable<Product> GVProducts_GetData(string Sort)
        {
            var query = _db.Products.AsQueryable();

            //Here I want filter my data 
            if (Sort == "1")
            {
                query = (here should select all the product which are in category 1)
            }
            else if (Sort == "2")
            {
                query = (here should select all the product which are in category 2)
            }
        return query;

}

【问题讨论】:

    标签: c# linq entity-framework ef-code-first


    【解决方案1】:
         DbContext.Category.Where(c => c.ID == 1)
          .Include(c => c.Products).Select(x => x.Products).ToList();
    

    可能是这样的。确保使用包含。

    【讨论】:

    • 请查看备注
    【解决方案2】:

    创建方法:

      public IEnumerable<Product> GetProducts(params int[] selectCategory )
       {               
         return repository.Query<Category>       
        (p => selectCategory.Contains(p.ID)).SelectMany(p => p.Products).ToList()
    
       }
    

    使用示例:

    var product = GetProducts(1,3,5);
    

    1,3,5 搜索类别

    【讨论】:

      猜你喜欢
      • 2013-02-07
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多