我正在做一个.Net MVC3项目。我有以下代码在同一表上运行 2 个查询。第二个查询取决于第一个查询的结果。如何重写它以使用单个查询(使用嵌套查询)并将结果分配给我的视图模型?
public ViewResult Category(string id)
{
var viewModel = new ProductCategoryNavigation();
viewModel.category = db.Category.Single(c=>c.NavigationId==id);
viewModel.subCategories = db.Category.Where(i => i.ParentId == category.Id);
return View(viewModel);
}
var query = (from c in db.Category.Where(x => x.NavigationId == id)
join sc in db.Category on c.Id equals sc.ParentId into g
select new {
Category = c,
SubCategories = g
}).Single();
viewModel.category = query.Category;
viewModel.subCategories = query.SubCategories;
如果有关系映射 Category-to-Category,你可以使用这样的东西。
viewModel.subCategories = db.Category.Single(c=>c.NavigationId==id).Category;
如果存在关系,您会看到 2 种不同的实现,如下所示:
Category.Category1 > return Category (parent)
Category.Category2 > return Collection of Category (children)
我认为你可以尝试这样的事情。
viewModel.subCategories = from c in db.categories
join c1 in db.categories on c.Id = c1.ParentId
where c.NavigationId = id
select c1