提问者:小点点

获取产品和类别的ViewModel


我正在开发一个电子商务网站,我使用三个表来管理产品和类别。

我需要一个或多个带有实体框架的linq查询来获得母类别列表、子类别列表和相关产品列表。

有一个类别表,如:

Id NameCat ParentId

有一个products表,如:

Id名称实时信息等。

有一个product-category表,如:

Id categoryId productId sortOrder

这是我的viewmodel

public class CatViewModel
    {
        public int IdCat { get; set; }
        public string NameCat { get; set; }
        public int ParentId { get; set; }
        public List<CatViewModel> Children { get; set; }
        public List<Product> Products { get; set; }

    }

显然,每个父类别必须有其所有子类别的产品的完整列表


共1个答案

匿名用户

You are on the right way, now in the method that is supposed to return view with this CatViewModel you can do this. 

var mainObject = Context.Category.FirstOrDefault(x => x.IdCat == "YOUR PARAMETER OF ID HERE");
var viewModel = new CatViewModel
{
   IdCat = mainObject.IdCat,
   NameCat = mainObject.NameCat,
   ParentId = mainObject.ParentId,
   Children = Context.Children(query here).ToList(),
   Products = Context.Products(query here).ToList()
};

Solution 2:

You can first create:

var listChildern = Context.Children(query here).ToList();
var listProducts = Context.Products(query here).ToList();

then you viewModel and you fill it just like this:

var mainObject = Context.Category.FirstOrDefault(x => x.IdCat == "YOUR PARAMETER OF ID HERE");
var viewModel = new CatViewModel
{
   IdCat = mainObject.IdCat,
   NameCat = mainObject.NameCat,
   ParentId = mainObject.ParentId,
   Children = listChildern ,
   Products = listProducts 
};