gpt4 book ai didi

c# - Entity Framework 是否支持多线程?

转载 作者:行者123 更新时间:2023-12-03 21:52:26 26 4
gpt4 key购买 nike

我正在编写一个面向 Entity Framework 6.1.3 的 C# .NET4.5 控制台应用程序。
我使用的工作单元范式如下:

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 数据库中的相同表。

我已经使用锁为我的其他代码实现了线程安全代码,但我不知道如何使实体线程安全?现在,我收到以下错误:
INNER EXCEPTION: New transaction is not allowed because there are other threads running in the session.
我在网上看过,并没有找到太多关于实体和多线程的信息。我听说 Entity 不支持多线程应用程序,但发现听说可以相信。任何指针将不胜感激。

最佳答案

DataContext 的文档状态:

Any instance members are not guaranteed to be thread safe.



这也是我所经历的。我试图做你正在做的事情,我看到了一些奇怪的错误,这些错误支持它不是线程安全的想法。

您必须在每个线程中创建一个新的 DataContext 实例。

关于c# - Entity Framework 是否支持多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36854087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com