Anonymous
Anonymous

Reputation: 1979

ASP.NET MVC Query to ViewModel

I have a very simple ViewModel (ProductViewModel)

 public class ProductViewModel
 {
    public int ProductID { get; set; }
    public int CategoryID { get; set; }
    public string ProductName { get; set; }
    public string CategoryName { get; set; }
 }

In my controller I'm grabbing a specific Product

var product = _context.Products
            .Select(p => new ViewModels.ProductViewModel
            {
                CategoryID = p.Category.CategoryID,
                ProductID = p.ProductID,
                ProductName = p.ProductName,
                CategoryName = p.Category.CategoryName
            }).Where(p => p.ProductID == id);
        return View(product);

In my view I'm defining the model as

@model MvcApplication1.ViewModels.ProductViewModel

However, I'm getting this error:

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[MvcApplication1.ViewModels.ProductViewModel]', but this dictionary requires a model item of type 'MvcApplication1.ViewModels.ProductViewModel'.

I'm not sure why it's throwing that error since I am passing ProductViewModel into the view...At least is looks like I am. Any guidance would be appreciated

Thanks!

Upvotes: 0

Views: 928

Answers (1)

user2453734
user2453734

Reputation:

You need to execute the query to get the actual object type back. Calling FirstOrDefault() or ToList() will execute the query. There is also .First(), it throws an exception if the item is not found after the query is executed.

Try this:

 Select(p => new ViewModels.ProductViewModel
{
    CategoryID = p.Category.CategoryID,
    ProductID = p.ProductID,
    ProductName = p.ProductName,
    CategoryName = p.Category.CategoryName
}).Where(p => p.ProductID == id).FirstOrDefault();//Executes the query

Looping the result set will also execute the query. So, if you did something like below, you would not need to call FirstOrDefault() or ToList().

foreach(var item in product)//IF YOU HAVE MULTIPLE ITEMS
     item.//THIS IS A SINGLE PRODUCTVIEWMODEL INSTANCE NOW

Upvotes: 2

Related Questions