Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert model to viewmodel [duplicate]

I have a table name "Product" and another table name "category". Product table has 'productID', 'productName' and 'CategoryID'. Category table has 'categoryID' and 'categoryName'.

My target is to display a list of products with category. The list will contain 'product id', 'product name' and 'category name'.

I have created a viewmodel. the code is

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

In my controller, I have:

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

How would I write my controller code so that it matches with the viewmodel??

like image 723
Crime Master Gogo Avatar asked Sep 08 '25 17:09

Crime Master Gogo


1 Answers

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));
}
like image 154
krolik Avatar answered Sep 10 '25 08:09

krolik