I have setup a couple of objects:
Product.cs
namespace Print_Solutions.Models
{
public class Product
{
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string PartNumber { get; set; }
public int ProductCategoryID { get; set; }
public virtual ICollection<ProductCategory> ProductCategory { get; set; }
}
}
ProductCategory.cs
namespace Print_Solutions.Models
{
public class ProductCategory
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
The DB Context
namespace Print_Solutions.DAL
{
public class ApplicationContext : DbContext
{
public ApplicationContext() : base("DefaultConnection")
{
}
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductDetail> ProductDetails { get; set; }
public DbSet<ProductDocument> ProductDocuments { get; set; }
public DbSet<ProductImage> ProductImages { get; set; }
public DbSet<RelatedProduct> RelatedProducts { get; set; }
}
}
The Controller
namespace Print_Solutions.Controllers
{
public class DashboardController : Controller
{
private ApplicationContext db = new ApplicationContext();
public ActionResult Index()
{
ViewBag.Products = db.Products.ToList();
ViewBag.ProductCategories = db.ProductCategories.ToList();
return View();
}
}
}
The Problem
I have tried a couple of things in the view. Neither one of these seems to work. How can I access products from productcategories, and vice versa?
<ul>
@foreach(Print_Solutions.Models.ProductCategory category in @ViewBag.ProductCategories)
{
<li>@category.Name
<ul>
@foreach(var product in @category.Products)
{
<li>@product.Name</li>
}
</ul>
</li>
}
</ul>
or
<ul>
@foreach (Print_Solutions.Models.Product product in @ViewBag.Products)
{
<li>@product.Name - @product.ProductCategory.Name</li>
}
</ul>
I can access products, and product categories, but not through their related objects. What am I missing?