I am working for EF 4.2 code first and have been getting a lot of random context connection issues, and wondered if you could cast an eye over this implementation and then slap my wrists for doing it wrong (if it is wrong that is)
I have developed a repository pattern for this project.
I am sure the way I am doing it is the problem, but anyway here is the code:
Context Provider
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;
}
}
}
Here is my repository:
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 Class
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 ....
}
I think the issue is the static Context, am I right? and if so what is the solution?