我正在编写针对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的文档指出:
不保证任何实例成员都是线程安全的。
这也是我所经历的。我尝试做您正在做的事情,并且看到了奇怪的错误,这些错误支持了线程不安全的想法。
您将必须在每个线程中创建一个新的DataContext实例。
如何排序List <Entity>? - c#假设我有一个列表:MyList = new List<MyEntity>(); 然后我尝试将项目添加到列表中。 WCF RIA服务通过异步调用加载的每个项目。在添加任何新项目之后,我希望MyList始终按MyEntity的属性进行排序,例如ID。如何解决这个问题? 参考方案 您可以使用SortedSet使其保持排序 SortedSet<in…
将谓词<T>转换为Func <T,bool> - c#我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…
通过Maven编译器插件不会发生有限的包含和排除 - java我正在使用3.6.0版的maven编译器插件,在此我们只想在特定文件夹中编译一个文件,而在该位置编译所有其他文件。例如:在文件夹应用程序中有14个文件,从那我只希望编译1个文件,但它编译了所有文件,如果我要排除,则它也不起作用。 <sourceDirectory>${basedir}/../src/java</sourceDirectory…
Java中的<<或>>>是什么意思? - javaThis question already has answers here: Closed 7 years ago. Possible Duplicate: What does >> and >>> mean in Java?我在一些Java代码中遇到了一些陌生的符号,尽管代码可以正确编译和运行,但对于括号在此代码中的作用却感…
当我所有的都是T时,如何返回Interface <T>的实例? - java我有一个界面:public interface ILoginResult<T> { public T get(); } 我有一个LoginPage对象:public class LoginPage<T> { ... public ILoginResult<T> login(...) { ... } } 我也有一些登录页面对…