针对多个DB事务使用存储库和工作单元模式的C#实体框架
本文关键字:单元 工作 模式 框架 实体 存储 DB 事务 | 更新日期: 2023-09-27 18:24:31
我定义了三个表,Parts
、Models
和PartModel
。对于每个Part
行,可以定义多个Models
行,并且它们通过PartModel
表以关系连接。
零件
ID PartName
1 Motorcycle
2 Cars
型号
ID ModelName
1 Suzuki
2 Yamaha
3 Toyota
4 Nissan
零件模型
ID PartID ModelID
1 1 1
2 1 2
3 2 3
4 2 4
C#型号
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
namespace TestApplication.Model
{
[Table("Parts")]
public partial class Parts
{
[Key]
public int PartID { get; set; }
[Required]
[StringLength(50)]
public string PartName { get; set; }
}
[Table("Models")]
public partial class Models
{
[Key]
public int ModelID { get; set; }
[Required]
[StringLength(50)]
public string ModelName { get; set; }
}
[Table("PartModel")]
public partial class PartModel
{
[Key]
public int PartModelID { get; set; }
public int PartID { get; set; }
public int ModelID { get; set; }
}
}
下面是我的存储库类:
BaseRepository.cs
using System;
using System.Transactions;
namespace TestApplication.Data
{
public abstract class BaseRepository<TContext> : IDisposable
where TContext : class, new()
{
private readonly bool startedNewUnitOfWork;
private readonly IUnitOfWork<TContext> unitOfWork;
private readonly TContext context;
private bool disposed;
public BaseRepository()
: this(null)
{
}
public BaseRepository(IUnitOfWork<TContext> unitOfWork)
{
if (unitOfWork == null)
{
this.startedNewUnitOfWork = true;
this.unitOfWork = BeginUnitOfWork();
}
else
{
this.startedNewUnitOfWork = false;
this.unitOfWork = unitOfWork;
}
this.context = this.unitOfWork.Context;
this.disposed = false;
}
~BaseRepository()
{
this.Dispose(false);
}
protected TContext Context
{
get
{
return this.context;
}
}
public IUnitOfWork<TContext> UnitOfWork
{
get
{
return this.unitOfWork;
}
}
public void Commit()
{
this.unitOfWork.Commit();
}
public void Rollback()
{
this.unitOfWork.Rollback();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
DisposeManagedResources();
}
this.disposed = true;
}
}
protected virtual void DisposeManagedResources()
{
if (this.startedNewUnitOfWork && (this.unitOfWork != null))
{
this.unitOfWork.Dispose();
}
}
public IUnitOfWork<TContext> BeginUnitOfWork()
{
return BeginUnitOfWork(IsolationLevel.ReadCommitted);
}
public static IUnitOfWork<TContext> BeginUnitOfWork(IsolationLevel isolationLevel)
{
return new UnitOfWorkFactory<TContext>().Create(isolationLevel);
}
}
}
IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace TestApplication.Data
{
public interface IRepository<TContext, TEntity, TKey>
where TContext : class
where TEntity : class
{
IUnitOfWork<TContext> UnitOfWork { get; }
List<TEntity> Find(Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderByMethod = null, string includePaths = "");
TEntity FindByID(TKey id);
List<TEntity> FindAll();
void Add(TEntity entity, Guid userId);
void Update(TEntity entity, Guid userId);
void Remove(TKey id, Guid userId);
void Remove(TEntity entity, Guid userId);
}
}
Repository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace TestApplication.Data
{
public class Repository<TContext, TEntity, TKey> : BaseRepository<TContext>, IRepository<TContext, TEntity, TKey>
where TContext : class, new()
where TEntity : class
{
private readonly DbSet<TEntity> _dbSet;
private DbContext CurrentDbContext
{
get
{
return Context as DbContext;
}
}
public Repository()
: this(null)
{
}
public Repository(IUnitOfWork<TContext> unitOfWork)
: base(unitOfWork)
{
_dbSet = CurrentDbContext.Set<TEntity>();
}
public virtual List<TEntity> Find(Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderByMethod = null, string includePaths = "")
{
IQueryable<TEntity> query = _dbSet;
if (predicate != null)
query = query.Where(predicate);
if (includePaths != null)
{
var paths = includePaths.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
query = paths.Aggregate(query, (current, path) => current.Include(path));
}
var entities = orderByMethod == null ? query.ToList() : orderByMethod(query).ToList();
return entities;
}
public virtual TEntity FindByID(TKey id)
{
var entity = _dbSet.Find(id);
return entity;
}
public virtual List<TEntity> FindAll()
{
return Find();
}
public virtual void Add(TEntity entity, Guid userId)
{
if (entity == null)
throw new ArgumentNullException("entity");
_dbSet.Add(entity);
}
public virtual void Update(TEntity entity, Guid userId)
{
if (entity == null) throw new ArgumentNullException("entity");
_dbSet.Attach(entity);
CurrentDbContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Remove(TKey id, Guid userId)
{
var entity = _dbSet.Find(id);
Remove(entity, userId);
}
public virtual void Remove(TEntity entity, Guid userId)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (CurrentDbContext.Entry(entity).State == EntityState.Detached)
_dbSet.Attach(entity);
_dbSet.Remove(entity);
}
}
}
零件pository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;
namespace TestApplication.Data
{
public class PartsRepository : Repository<DBContext, Parts, int>
{
public PartsRepository() : this(null) { }
public PartsRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }
}
}
模型假设.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;
namespace TestApplication.Data
{
public class ModelsRepository : Repository<DBContext, Models, int>
{
public ModelsRepository() : this(null) { }
public ModelsRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }
}
}
PartModelRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;
namespace TestApplication.Data
{
public class PartModelRepository : Repository<DBContext, PartModel, int>
{
public PartModelRepository() : this(null) { }
public PartModelRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }
public PartModel GetPartModelByModelID(ModelID)
{
// LINQ Query here to get the PartModel object based on the ModelID
var q = (from a in this.Context.PartModel.Where(a => a.ModelID == ModelID)
select a);
PartModel partModel = q.FirstOrDefault();
return partModel;
}
}
}
我需要做的是使用存储库说,例如,我想删除模型1(Suzuki),我可以在一个事务中执行多个表删除,这样我就可以确保数据将从Model
和PartModel
两个表中删除。
目前,我的代码如下(这很有效,但请注意,我正在进行两次Repository调用,这样一来,一个事务可能会失败,但对数据库的更改仍然会被推送到另一个Repository调用上):
public bool DeleteModel(int ModelID)
{
// Get the PartModel based on the ModelID
using(PartModelRepository partModelRepo = new PartModelRepository())
{
PartModel partModel = partModelRepo.GetPartModelByModelID(ModelID);
partModelRepo.Remove(partModel, Guid.NewGuid());
partModel.Commit();
}
// Delete the Model
using(ModelsRepository modelRepo = new ModelsRepository())
{
Models model = modelRepo.FindByID(ModelID);
modelRepo.Remove(model, Guid.NewGuid());
modelRepo.Commit();
}
}
我该如何翻译它,以便为两个DB删除命令都有一个Commit
?
我尝试了以下方法:
public bool DeleteModel(int ModelID)
{
// Get the PartModel based on the ModelID
using(ModelsRepository modelsRepo = new ModelsRepository())
{
using(PartModelRepository partModelRepo = new PartModelRepository(modelsRepo.UnitOfWork))
{
PartModel partModel = partModelRepo.GetPartModelByModelID(ModelID);
partModelRepo.Remove(partModel, Guid.NewGuid());
Models model = modelRepo.FindByID(ModelID);
modelRepo.Remove(model, Guid.NewGuid());
modelRepo.Commit();
}
}
}
但它抛出了一个关于FK约束违反的错误。
我确实理解我正在删除PartModel
和Model
,但它似乎不能将这两个删除操作合并到一个事务操作中。
感谢您的意见。
更新
正如一些人在这里发布的那样,我已经更新了我的代码,以使用微软推荐的交易。
public bool DeleteModel(int ModelID)
{
// Get the PartModel based on the ModelID
using (var transaction = this.Context.Database.BeginTransaction())
{
PartModel partModel = this.Context.PartModel.First(s => s.ModelID == ModelID);
Models model = this.Context.Models.First(s => s.ModelID == ModelID);
this.Context.PartModel.Remove(partModel);
this.Context.Models.Remove(model);
this.Context.SaveChanges();
transaction.Commit();
}
return true;
}
我使用MS SQL Profiler跟踪了数据库调用,并且发出的命令是正确的。我遇到的问题是,这些更改似乎没有持久化到数据库中。
我在上面的代码上使用了try-catch块,但没有抛出错误,因此,我知道操作是可以的。
有什么想法吗?
DbContext
知道环境事务。
要显示,请在项目中引用System.Transactions
,并将所有操作包含在这样的块中,该块实例为TrasnactionScope:
using(var ts = new TransactinScope())
{
// inside transaction scope
// run all the transactional operations here
// call .Complete to "commit" them all
ts.Complete();
}
如果出现异常,或者没有调用ts.Complete()
,或者显式调用ts.Dispose()
,则事务(即块内的所有操作)将回滚。
例如,您可以修改public bool DeleteModel(int ModelID)
,包括一个包装所有操作的using
,它们将共享同一事务。
更新:
为了给这个答案添加更多内容,因为我主要执行与数据相关的更改,所以我选择了使用Database.BeginTransaction.
您可以使用.Net的TransactionScope类来执行多数据库事务。您仍然需要在事务中分别对每个上下文调用SaveChanges(),但在外部TransactionScope上调用Commit()将完成最后的提交。
至于您的fk冲突,我建议使用SqlServer探查器或DB拦截器来跟踪EF正在执行的查询。有时,您需要更明确地告诉EF删除依赖项:跟踪应该可以很容易地告诉要删除的是什么。另一件需要注意的事情是,EF默认情况下假设FK关系为"删除时级联"。如果您在配置中没有禁用此功能,并且EF不是生成DB的人,那么这种不匹配可能会导致EF认为它需要发出比实际需要更少的删除查询。