I have problem with consuming DbContext class in EF 4.3 CodeFirst approach.
As for now I have created repository that contains all methods needed to get/put things from/into database. The problem is that all of that methods must wrap around a code like this:
using(var context = new MyDbContext())
{
//some code here to run on database
}
I have, however, no idea how to refactor this to single class that does all of initialization and disposes after each query. I have also heard that I shouldn’t use static field for DbContext (which I eventually did and it worked, but also not elegant solutio). I have not found any constructive info on web as well as no book explains how to do this in elegant way.
Thank you in advance for help.
Try to use the approach called “DbContext per Request”. You basically create an instance of DbContext on demand, attach it to HttpContext and then you check during Application_EndRequest if the instance exists and if yes, dispose of it.
RequestContext.cs
Global.asax.cs
Example usage: