MVC + EF4 + POCO - How to save Entity Context contents?

I am starting an MVC project by going through the MvcMusicStore tutorial. I am trying to understand how the data / entity context created by POCO should be saved.

In the samples, the controller generates a copy of the entity context, and all operations are completed there:

MusicStoreEntities storeDB = new MusicStoreEntities(); // // GET: /Store/ public ActionResult Index() { // Retrieve list of Genres from database var genres = from genre in storeDB.Genres select genre.Name; [...] 

If I need to split my solution into layers, what is the standard practice (or key options) to keep the context? Can I generate it in the controller and transfer it to the repository, or can the repository store a public copy?

I understand that the above would be necessary to use the unit of work template.

My layers:

  • Data (edmx file)
  • Objects (created from POCO)
  • Repository
  • Mvc Web Application

My other questions: - What are the overheads of creating a context? - Since there is no .Close (), and it does not implement IDisposable, is the ObjectContext behind its creation of separate connections, connection pool, sharing of one instance? - Is it possible to lock an ObjectContext if it has gone too far between layers / operations?

Thanks in advance.

+4
source share
2 answers

I don't want to go into details or code, so I just mentioned some points:

  • Your controller can work with multiple repositories
  • There must be one repository for each root placeholder
  • Controller operation between several repositories becomes possible thanks to Unit of Work
  • Use the DI container to manage the Unit of Work life cycle (which is actually the context).
  • Do not use singletones for context, let DI container instantiate / delete context for HTTP request
+6
source

I create a single repository for each controller and place my context there. The rules that I follow are that the repository processes everything that I could make fun of (not exactly the definition of a repository, but it works for me). If necessary, the repository can call other repositories, but the dispatcher does not need to know about it. Context is a property of a repository instance and is created on demand (I have not made a jump in IOC yet). If the repository calls another repository, it passes the context instance.

It is a bit like this ...

 public class MyController : Controller { public IMyControllerRepository Repository { get; set; } public ActionResult MyAction(int id) { var model = Repository.GetMyModel(id); return View(model); } } public class MyControllerRepository : IMyControllerRepository { public MyContext Context { get; set; }; public MyModel GetMyModel(int id) { return (from m in Context.MyModels where m.ID = id select m).SingleOrDefault(); } } 
+2
source

All Articles