我开发了一个 ASP.NET 的MVC应用程序来管理项目,使用实体框架6.0和存储库设计模式。现在,我想集成事务,以确保某些插入/更新数据库操作遵循 ACID 主体,尤其是原子性主体。
以下是我的通用存储库的片段:
1. 通用存储库接口
public interface IGenericRepository<T> : IRepository where T : BaseEntity
{
void Create(T entity);
void Delete(T entity);
IEnumerable<T> GetAll();
void Update(T entity);
}
2. 通用存储库类
public abstract class GenericRepository<T> : IGenericRepository<T> where T : BaseEntity
{
protected IContext _context;
protected IDbSet<T> _dbset;
public GenericRepository(IContext context)
{
_context = context;
_dbset = _context.Set<T>();
}
public virtual void Create(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_dbset.Add(entity);
_context.SaveChanges();
}
public virtual void Update(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();
}
public virtual void Delete(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_dbset.Remove(entity);
_context.SaveChanges();
}
public virtual IEnumerable<T> GetAll()
{
return _dbset.AsEnumerable<T>();
}
}
3. 我的上下文实现
public interface IContext
{
IDbSet<Projet> Projects { get; set; }
IDbSet<Task> Tasks{ get; set; }
IDbSet<Entite> Entities { get; set; }
DbSet<TEntity> Set<TEntity>() where TEntity : class;
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
int SaveChanges();
}
4. 项目实体
public class ProjectRepository : GenericRepository<Projet>, IProjectRepository
{
IContext _context;
public ProjectRepository(IContext context) : base(context)
{
_context = context;
_dbset = _context.Set<Projet>();
}
public Projet GetProjectById(int Id)
{
return _dbset.FirstOrDefault(x=>x.Id == Id);
}
}
所以,我想做的是让事务与上面的模型一起工作。例如,当使用他的任务创建项目时,我想使用事务来保存项目和任务实体,因此我确信插入这些实体将是原子操作。
感谢您的帮助和建议。
通常,您的存储库会注入到引擎/服务类中。我假设我们有一个ProjectEngine.cs其中注入了ProjectRepo和TaskRepo。代码将如下所示:
public class ProjectEngine : IProjectEngine
{
IProjectRepository projectRepository;
ITaskRepository taskRepository;
public ProjectEngine(
IProjectRepository ProjectRepository,
ITaskRepository TaskRepository)
{
projectRepository = ProjectRepository;
taskRepository = TaskRepository;
}
public void CreateProject(CreateProjectRequest createProjectRequest)
{
using (TransactionScope scope = new TransactionScope())
{
// these operations are atomic since they below to same transactionscope
projectRepository.Add([project]);
taskRepository.Add([tasks]);
// data will not be affected until complete operation is called. Any database exception would rollback the transaction.
scope.Complete();
}
}
}
回顾一下,最好的方法是在同一事务范围内包含多个存储库操作。