Entity Framework ObjectContext re-usage

后端 未结 6 556
我寻月下人不归
我寻月下人不归 2020-12-24 15:45

I\'m learning EF now and have a question regarding the ObjectContext:

Should I create instance of ObjectContext for every query (function) when I access the database

6条回答
  •  隐瞒了意图╮
    2020-12-24 16:05

    I think the most common way is to use it per request. Create it at the beginning, do what you need (most of the time these are operation that require common ObjectContext), dispose at the end. Most of DI frameworks support this scenario, but you can also use HttpModule to create context and place it in HttpContext.Current.Items. That is simple example:

    public class MyEntitiesHttpModule : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.BeginRequest += ApplicationBeginRequest;
            application.EndRequest += ApplicationEndRequest;
        }
    
        private void ApplicationEndRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Items[@"MyEntities"] != null)
                ((MyEntities)HttpContext.Current.Items[@"MyEntities"]).Dispose();
        }
    
        private static void ApplicationBeginRequest(Object source, EventArgs e)
        {
            var context = new MyEntities();
            HttpContext.Current.Items[@"MyEntities"] = context;
        }
    }
    

提交回复
热议问题