Loading related object in MVC can be pretty confusing.
There are lots of terms you need to be aware of and learn if you really want to know what you're doing when writing your entity model classes and controllers.
A couple of questions that I've had for a very long time are: How does the virtual
keyword work and when should I use it? And how does the Include
extension method work and when should I use it?
Here's what I'm talking about;
virtual
keyword:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LazyLoading.Models
{
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public int ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
}
And the Include
extension method:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LazyLoading.Models;
namespace LazyLoading.Controllers
{
public class LazyLoadingStoreController : Controller
{
private UsersContext db = new UsersContext();
//
// GET: /LazyLoadingStore/
public ActionResult Index()
{
var brands = db.Brands.Include(b => b.Manufacturer);
return View(brands.ToList());
}
... Other action methods ...
Notice that the Index()
action method is autogenerated by Visual Studio. Yes, Visual Studio automatically added the .Include(b => b.Manufacturer)
. That's pretty nice.