Consuming dbcontext

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.

Answers


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

internal static class RequestContext
{
    internal static MyDbContext Current
    {
        get
        {
            if (!HttpContext.Current.Items.Contains("myContext"))
            {
                HttpContext.Current.Items.Add("myContext", new MyDbContext());
            }
            return HttpContext.Current.Items["myContext"] as MyDbContext;
        }
    }
}

Global.asax.cs

protected void Application_EndRequest(object sender, EventArgs e)
{
     var entityContext = HttpContext.Current.Items["myContext"] as MyDbContext;
     if (entityContext != null)
         entityContext.Dispose();
}

Example usage:

public class MyDbAccessClass
{
    public static List<Products> GetProducts()
    {
         var products = from o in RequestContext.Current.Products
                        select o;
         return products.ToList();
    }
}

Need Your Help

extract every n row in a matrix to another matrix in a loop

matlab loops matrix extract

I'm a total beginner to matlab and I'm currently writing a script for extracting data from a thermographic video.

Reflux: component does not get the triggered event from store

reactjs refluxjs

Following a good React course from udemy, I used Reflux to create a store, however, the triggered event from the store can not be caught by the component.