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