VsMaX
VsMaX

Reputation: 1795

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.

Upvotes: 0

Views: 574

Answers (1)

walther
walther

Reputation: 13600

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();
    }
}

Upvotes: 1

Related Questions