C# 关于如何访问我的DataContext(以及它是否错误)
我使用以下,C# 关于如何访问我的DataContext(以及它是否错误),c#,model-view-controller,design-patterns,C#,Model View Controller,Design Patterns,我使用以下,静态类来访问应用程序中的数据上下文 public static class DataContext { internal const string _contextDataKey = "dataContext"; /// <summary> /// Returns a unique data context that lives for the duration of the request, which can be from ASP.NET
静态类
来访问应用程序中的数据上下文
public static class DataContext
{
internal const string _contextDataKey = "dataContext";
/// <summary>
/// Returns a unique data context that lives for the duration of the request, which can be from ASP.NET or a WCF service
/// </summary>
/// <returns>The entity data model context for the current request</returns>
public static EntityDataModelContext GetDataContext()
{
IPersistanceContainer state;
if (HttpContext.Current != null)
{
state = new AspNetPersistanceContainer();
}
else if (OperationContext.Current != null)
{
state = new WcfPersistanceContainer();
}
else
{
state = new StaticPersistanceContainer(); // this container is thread-unsafe.
}
EntityDataModelContext edm = state.Get<EntityDataModelContext>(_contextDataKey);
if (edm == null)
{
edm = new EntityDataModelContext();
state.Store(_contextDataKey, edm);
}
return edm;
}
}
当我需要访问context
时,我只需调用DataContext.GetDataContext()
并访问数据库,我从不使用语句添加任何
如果我使用
语句添加一个,那么上下文
就可以一次使用,下次我尝试使用它时,它就被丢弃了。提出一个例外
如果我现在不这样做,这会让我有点不开心,我觉得这样做也不对,不处理它
所以我想知道在这里做什么才是正确的
这个设计有缺陷吗?我应该完全放弃吗
我是否应该想出一种方法,在处理上下文时重新创建上下文
我应该让设计保持原样吗
也许设计“足够好”,你有什么书推荐我读吗?我觉得我在后端体系结构方面的技能比较欠缺。在asp.net应用程序中,一个解决方案可以是这样的:
在请求开始时创建上下文
在请求结束时处理它
这篇文章讨论了这种方法(对于NHibernate会话管理,但对于EF几乎是一样的)
internal class AspNetPersistanceContainer : IPersistanceContainer
{
public T Get<T>(string key) where T : class
{
if (HttpContext.Current.Items.Contains(key))
return (T)HttpContext.Current.Items[key];
return null;
}
public void Store(string key, object value)
{
HttpContext.Current.Items[key] = value;
}
}