convert model to viewmodel [duplicate]

谁说我不能喝 提交于 2019-12-03 21:24:12

Maybe you will use your view model class directly:

       var query = from p in dc.Product
                    select new ProductIndexViewModel() { 
                        prodID = p.ProductID, 
                        prodName = p.ProductName, 
                        catName = p.Category1.CategoryName 
                    };

        List<ProductIndexViewModel> productForView = query.ToList();

You can use AutoMapper instead of rewriting properties from db model.

var viewModel = new ProductIndexViewModel()
{  
    ProductList = dc.Product.ToList().Select(product => Mapper.Map<Product, ProductViewModel>(product));
}

Should prodName and catName be strings?

Also, why not just do this:

var viewModel = dc.Product
    .ToList()
    .Select(x => new ProductIndexViewModel { prodID = x.ProductId, ... }

return View(viewModel);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!