using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Transactions; namespace CY_DocumentSynchroWCFService { /// /// 集合单元事务处理具体实现 /// public class UnitOfWorkForSql : IUnitOfWork { private Dictionary addedEntities; private Dictionary changedEntities; private Dictionary deletedEntities; public UnitOfWorkForSql() { addedEntities = new Dictionary(); changedEntities = new Dictionary(); deletedEntities = new Dictionary(); } /// /// 修改 /// /// /// public void RegisterAmended(IAggregateRoot entity, ICommonDAL unitofWorkRepository) { if (!changedEntities.ContainsKey(entity)) { changedEntities.Add(entity, unitofWorkRepository); } } /// /// 新增 /// /// /// public void RegisterNew(IAggregateRoot entity, ICommonDAL unitofWorkRepository) { if (!addedEntities.ContainsKey(entity)) { addedEntities.Add(entity, unitofWorkRepository); }; } /// /// 删除 /// /// /// public void RegisterRemoved(IAggregateRoot entity, ICommonDAL unitofWorkRepository) { if (!deletedEntities.ContainsKey(entity)) { deletedEntities.Add(entity, unitofWorkRepository); } } /// /// 事务提交 /// public bool Commit() { bool isSuccess = true; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { foreach (IAggregateRoot entity in this.addedEntities.Keys) { isSuccess = this.addedEntities[entity].InserModel(entity); if (!isSuccess) break; } if (isSuccess) { foreach (IAggregateRoot entity in this.changedEntities.Keys) { isSuccess = this.changedEntities[entity].UpdateModel(entity); if (!isSuccess) break; } } if (isSuccess) { foreach (IAggregateRoot entity in this.deletedEntities.Keys) { isSuccess = this.deletedEntities[entity].DeleteModel(entity); if (!isSuccess) break; } } if (isSuccess) scope.Complete(); } return isSuccess; } } }