2011-09-05 94 views
3

我有一个表名“Product”和另一个表名“category”。 产品表具有'productID','productName'和'CategoryID'。 类别表有'categoryID'和'categoryName'。convert model to viewmodel

我的目标是显示产品类别列表。该列表将包含“产品ID”,“产品名称”和“类别名称”。

我创建了一个viewmodel。代码

public int prodID{get;set;} 
public int prodName{get;set;} 
public int catName{get;set;} 

在我的控制,我有:

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); 

我怎么会写我的控制器代码,以便它与视图模型相匹配?

回答

5

也许你会直接使用您的视图模型类:

 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(); 
+0

谢谢。有用。 – kandroid

1

应该prodNamecatName是字符串吗?

而且,为什么不只是这样做:

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

return View(viewModel); 
5

您可以使用AutoMapper,而不是从DB模式改写性能。

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

我在WCF中使用Automapper,但我无法将实体模型与数据合同模型进行映射,我应该怎么做?这是我尝试:'requestDC = dbEntity.RequestDetails.ToList()。Select(req => Mapper.Map (req));'/ /我无法访问dbEntity.RequestDetails在Mapper.Map下 –