5

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

David Pine
  • 23,787
  • 10
  • 79
  • 107
user2985240
  • 95
  • 2
  • 8
  • 1
    Looks like the `Category` property has not been set. Could be the underlying entity framework you are using. You do use `Include` so I expect the problem to be in the entity framework mappings itself. – Myrtle Jan 22 '16 at 17:56

1 Answers1

2

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

ocuenca
  • 38,548
  • 11
  • 89
  • 102