我有两个类,形成多对多的关系。
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;
}
答案 0 :(得分:2)
DbContext.Category.Where(c => c.ID == 1)
.Include(c => c.Products).Select(x => x.Products).ToList();
可能是这样的。请务必使用Include。
答案 1 :(得分:1)
创建方法:
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寻求类别