Reputation: 21
I have an ASP.net MVC project which uses EF. I created entities also repository part. In my localhost, everything is fine and works without any problem. But when I removed this project to webhost, something is going wrong I guess.
"The context cannot be used while the model is being created.this exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accepted by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe."
Not everytime but sometimes I get this error when I try to connect my website.
Here is my Repository.cs
public class Repository<T> : IDataAccess<T> where T : class
{
private DatabaseContext context;
private DbSet<T> _objectSet;
public Repository()
{
context = RepositoryBase.CreateContext();
_objectSet = context.Set<T>();
}
public List<T> List()
{
return _objectSet.ToList();
}
public IQueryable<T> ListQueryable()
{
return _objectSet.AsQueryable<T>();
}
public List<T> List(Expression<Func<T, bool>> where)
{
return _objectSet.Where(where).ToList();
}
}
Here is my RepositoryBase.cs
public class RepositoryBase
{
private static DatabaseContext context;
private static object _lockSync = new object();
protected RepositoryBase()
{
}
public static DatabaseContext CreateContext()
{
if (context == null)
{
lock (_lockSync)
{
if (context == null)
{
context = new DatabaseContext();
}
}
}
return context;
}
}
and my DatabaseContext :
public class DatabaseContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Soru> Sorular { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Kategori> Kategoriler { get; set; }
public DbSet<Tahmin> Tahminler { get; set; }
public DbSet<Oneri> Oneriler { get; set; }
public DatabaseContext()
{
Database.SetInitializer(new MyInitializer());
}
}
I researched this problem but unfortunately, I couldn't fix it. I don't understand what I'm doing wrong.
Upvotes: 2
Views: 1295
Reputation: 23234
Your DatabaseContext
instance is declared as static
within the RepositoryBase
class.
private static DatabaseContext context;
Because of this, all concurrent requests share the same instance,
resulting in multiple simultaneous operations on the DbContext
from different threads,
which is not supported.
Rework your code so that each request has its own instance
eg, by removing the static keyword.
If each request has its own instance, there's no need anymore to apply a lock.
Also make sure to call the Dispose
method on the DbContex
when it isn't needed anymore, eg. at the end of the webrequest.
Upvotes: 2