Entity Framework ObjectContext re-usage

后端 未结 6 586
我寻月下人不归
我寻月下人不归 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:16

    public class DBModel {
    
            private const string _PREFIX = "ObjectContext";
    
            // DBModel.GetInstance();
            public static ObjectContext GetInstance() {
                var key = CreateKey();
                HttpContext.Current.Items[key] = HttpContext.Current.Items[key] ?? Activator.CreateInstance();
                return HttpContext.Current.Items[key] as ObjectContext;
            }
    
            private static string CreateKey() {
                return string.Format("{0}_{1}", _PREFIX, typeof(T).Name);
            }
        }
    

提交回复
热议问题