Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance of an object in Razor View [duplicate]

I have 2 entities, namely Product and Category,

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<Product> Products { get; set; }  
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

Product Controller

public class ProductsController : Controller
    {
        private DemoContext db = new DemoContext();

        // GET: Products
        public ActionResult Index()
        {
            var products = db.Products.Include(p => p.Category);
            return View(products.ToList());
        }

        // GET: Products/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }
    }

I try to access the CategoryName Property from Category Entity in the Product Details View as this

<h2>@Model.Name</h2>
<label>@Model.Category.CategoryName</label>
<li>@Model.Price.ToString("##,###")</li>

But I got error "Object reference not set to an instance of an object."

@Model.Category.CategoryName

like image 781
user2985240 Avatar asked Oct 31 '22 10:10

user2985240


1 Answers

If you want to load Category navigation property as part of the query that you use to load a Product, you should change your query to this one:

Product product = db.Products.Include(p=>p.Category).FirstOrDefault(p=>p.ProductId ==id);

This is called eager loading and you can read more about it in this link

like image 52
octavioccl Avatar answered Nov 15 '22 06:11

octavioccl