尝试使用称为“每个请求的 DbContext”的方法。您基本上按需创建一个 DbContext 实例,将其附加到 HttpContext ,然后在 Application_EndRequest 期间检查该实例是否存在,如果存在,则将其丢弃。
请求上下文.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;
}
}
}
全球.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();
}
}