2012-06-13 57 views
0

我在EF 4.3 CodeFirst方法中使用DbContext类时遇到了问题。Consuming dbcontext

至于现在我已经创建了存储库,其中包含将数据从/中取出/放入数据库所需的所有方法。问题是,所有这些方法都必须围绕这样的代码包:

using(var context = new MyDbContext()) 
    { 
    //some code here to run on database 
    } 

我有,但是不知道如何重构这个单的类,它的所有的初始化和每次查询后处置。我也听说我不应该为DbContext使用静态字段(我最终这样做了,它的工作,但也不是优雅的解决方案)。我没有在网上找到任何建设性的信息,也没有任何书解释如何以优雅的方式做到这一点。

非常感谢您的帮助。

回答

2

尝试使用名为“每个请求的DbContext”的方法。您基本上根据需要创建DbContext实例,将其附加到HttpContext,然后在Application_EndRequest期间检查实例是否存在,如果是,请将其处理。

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

实例:

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