The problem is that when I hover a mouse over the db.Reviews.ToList();
to see if data is populated correctly or not I see red cross warnings inside the box and then right after stepping over null referrence exception is thrown. This doesn't happen and everything works fine if I don't check what's inside. Why is that happening? Do I retrieve the data in an improper way?
private DataContext db;
public HomeController()
{
db = new DataContext();
}
public ActionResult ProductView (int? id)
{
if (id != null)
{
var book = Details(id);
book.reviews = db.Reviews.ToList();
return View(book);
}
else
return HttpNotFound();
}
Details method is just a bridge method that more than one Action methods use
public HomeModel Details(int? id)
{
HomeModel model = new HomeModel();
var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).Include(b=> b.Category.Books).FirstOrDefault();
if (book == null)
{
HttpNotFound();
}
book.DisplayNumber++;
db.SaveChanges();
model.bookDetails = book;
return model;
}
HomeModel class is a wrapper that contains multiple classes to use in View:
public class HomeModel:ReviewModel
{
public List<BookModel> PopularBooks { get; set; }
public List<BookModel> BestSales { get; set; }
public List<Review> reviews { get; set; }
public Book bookDetails { get; set; }
}
The line that exception occured:
Line 101: {
Line 102: var book = Details(id);
Line 103: **book.reviews = db.Reviews.ToList();**
Line 104: return View(book);
Line 105: }