I am writing a C# .NET4.5 Console application targeting the Entity Framework 6.1.3. I am using the Unit Of Work paradigm as follows:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DataContext _context;
private readonly List<object> _repositories = new List<object>();
public UnitOfWork(DataContext context)
{
_context = context;
_context.Configuration.LazyLoadingEnabled = false;
}
public IRepository<T> GetRepository<T>() where T : class
{
//try to get existing repository
var repo = (IRepository<T>)_repositories.SingleOrDefault(r => r is IRepository<T>);
if (repo == null)
{
//if not found, create it and add to list
_repositories.Add(repo = new EntityRepository<T>(_context));
}
return repo;
}
public int Commit()
{
return _context.SaveChanges();
}
public bool AutoDetectChanges
{
get { return _context.Configuration.AutoDetectChangesEnabled; }
set { _context.Configuration.AutoDetectChangesEnabled = value; }
}
And my Repository like this:
public class EntityRepository<T> : IRepository<T> where T: class
{
protected readonly DbContext Context;
protected readonly DbSet<T> DbSet;
public EntityRepository(DbContext context)
{
Context = context;
DbSet = Context.Set<T>();
}
public IQueryable<T> All()
{
return DbSet;
}
….. other functions….
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = Context.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
}
I call these like this:
var rep = _uow.GetRepository<TableOfPies>();
rep.Add(Pie);
_uow.Commit();
My Console application has multiple threads, each of which will at some point want to Update / Edit / Add to the same tables in my cloud-based SQL Server database.
I have implemented thread-safe code for my other code using locks but I am not aware of how I can make Entity thread-safe? Right now, I get the following error:
INNER EXCEPTION: New transaction is not allowed because there are other threads running in the session.
I have looked online and have not been able to find much about Entity and multi-threading. I have heard that Entity does not support multi-threaded applications but find that heard to believe. Any pointers would be greatly appreciated.