0

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!

1
  • 2
    Hint, to see what the type of a variable is, highlight the last lambda method. Additionally, your query is set to return zero or more (beyond 1 even) but your view only expects a single item. Commented Feb 18, 2015 at 16:59

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Would there ever be an instance when I would not need to run FirstOrDefault, ToList, etc...?
There are times when you might or might not actually execute a query in which case you would not need to. Note: looping the query will also execute it, which does not require the call to FirstOrDefault() or ToList().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.