2011-09-05 152 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下 –