这个问题在这里已经有了答案:
Where to convert business model to view model?
(3 个回答)
3年前关闭。
我有一个表名“产品”和另一个表名“类别”。
产品表有“productID”、“productName”和“CategoryID”。
类别表具有“categoryID”和“categoryName”。
我的目标是显示带有类别的产品列表。该列表将包含“产品 ID”、“产品名称”和“类别名称”。
我创建了一个 View 模型。代码是
public int prodID{get;set;}
public int prodName{get;set;}
public int catName{get;set;}
在我的 Controller 中,我有:
var query= from p in dc.Product
select new {p.ProductID,p.ProductName,p.Category1.CategoryName };
var prod = new ProductIndexViewModel()
{
ProductList=query //this line is problematic !!it says an explicit conversion exists....
};
return View(prod);
我将如何编写 Controller 代码以使其与 View 模型匹配??
最佳答案
您可以使用 AutoMapper而不是从 db 模型重写属性。
var viewModel = new ProductIndexViewModel()
{
ProductList = dc.Product.ToList().Select(product => Mapper.Map<Product, ProductViewModel>(product));
}
关于model-view-controller - 将模型转换为 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7312012/