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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With