I created a simple CodeFirst (Entity Framework 4.1) context and then, using the right mouse button on the controller folder said : “Add Controller”, “Entity Framework”, picked one of my simple codefirst entities I created and the associated context. The controller code it genreated is as follows below.
What has me confused is why the Context is created as a private object in the Controller class. I would think that it should be create in a using() so that at the end of the method it could be disposed properly.
What am I missing here? I’m sure the guys who wrote this no what they are doing.
Thanks
namespace Web.Controllers
{
public class TaskInfoController : Controller
{
private TaskContext db = new TaskContext();
//
// GET: /TaskInfo/
public ViewResult Index()
{
var taskinfos = db.TaskInfos.Include(t => t.TaskGroup);
return View(taskinfos.ToList());
}
Well, this allows for atomic commits, but I agree, this is not the proper way. I use the Repository/Service/UnitOfWork pattern with MVC3 and EF and it works great. Search SO for it, there is a ton of info on it. In the meantime, move it into a using statement inside the controller action.