【发布时间】:2012-03-15 13:47:39
【问题描述】:
我首先为 EF 4.2 代码工作,并且遇到了很多随机上下文连接问题,想知道您是否可以关注一下这个实现,然后为我做错了拍我的手腕(如果它是错误的,那就是)
我已经为这个项目开发了一个存储库模式。
我确定我这样做的方式是问题所在,但无论如何这里是代码:
上下文提供者
public class ContextProvider
{
private static MyContext context;
public static MyContext Context
{
get
{
if (context == null)
{
context = new MyContext();
}
Database.SetInitializer<MyContext>(null);
//create the DB if it doesn't exist
if (!context.Database.Exists())
{
context.Database.Create();
context = new MyContext();
}
return context;
}
}
}
这是我的存储库:
public class DataRepository
{
protected MyContext Context;
public DataRepository(MyContext context = null)
{
Context = context ?? ContextProvider.Context;
}
public ProviderBase<Foo> FooProvider { get { return new ProviderBase<Foo>(); } }
public ProviderBase<Bah> BahProvider { get { return new ProviderBase<Bah>(); } }
}
ProviderBase 类
public class ProviderBase<T> : IProviderBase<T> where T : BaseClass
{
public Boolean UseCaching { get; set; }
public MyContext Context;
public ProviderBase(Boolean useCaching = true, MyContext context = null)
{
Context = context ?? ContextProvider.Context;
UseCaching = useCaching;
}
#region Implementation of IProviderBase<T>
protected DbSet<T> DbSet
{
get
{
return Context.Set<T>();
}
}
... methods here for CRUD ....
}
我认为问题在于静态上下文,对吗?如果是,解决办法是什么?
【问题讨论】:
-
@Craig 感谢您展示了如何使用 SO 的搜索功能,但我对此非常了解。我已经阅读了 SO 和其他网站上的数百篇文章,但我对我的问题的解决方案一无所知,因此我发布了这个问题。建设性的回复比简单地发布链接更有帮助......
-
您正在构建什么类型的应用程序?
-
它是一个具有 N 层架构的大型网络应用程序
标签: entity-framework c#-4.0 ef-code-first datacontext