4

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??

Reza.Hoque
  • 2,690
  • 10
  • 49
  • 78

3 Answers3

7

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));
}
krolik
  • 5,712
  • 1
  • 26
  • 30
  • I'm using Automapper in WCF but i'm not able to map Entity model with Model of data contract,what i should do?? This is what i tried: `requestDC = dbEntity.RequestDetails.ToList().Select(req => Mapper.Map(req));` //I'm not able to access dbEntity.RequestDetails under Mapper.Map – Vishal I P Nov 07 '14 at 07:39
5

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();
Samich
  • 29,157
  • 6
  • 68
  • 77
1

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);
David Wick
  • 7,055
  • 2
  • 36
  • 38