实体框架是否支持多线程? [英] Does Entity Framework support Multi-Threading?
问题描述
我正在编写一个针对Entity Framework 6.1.3的C#.NET4.5控制台应用程序. 我使用的是工作单位范式,如下所示:
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; }
}
我的存储库是这样的:
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);
}
}
}
我这样称呼这些:
var rep = _uow.GetRepository<TableOfPies>();
rep.Add(Pie);
_uow.Commit();
我的控制台应用程序具有多个线程,每个线程在某个时候都希望更新/编辑/添加到基于云的SQL Server数据库中的相同表中.
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.
我已经使用锁为其他代码实现了线程安全代码,但是我不知道如何使Entity线程安全?现在,我收到以下错误:
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.
我在网上看了很多,但是没有找到关于实体和多线程的更多信息.我听说Entity不支持多线程应用程序,但相信它.任何指针将不胜感激.
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.