繁体   English   中英

使用存储库和工作单元模式进行多个DB事务的C#实体框架

[英]C# Entity Framework Using the Repository and Unit of Work Pattern for Multiple DB Transactions

我定义了三个表PartsModelsPartModel 对于每个“ Part行,可能定义了多个“ Models行,并且它们通过“ PartModel表以关系形式连接。

部分

ID  PartName
1   Motorcycle
2   Cars

楷模

ID  ModelName
1   Suzuki
2   Yamaha
3   Toyota
4   Nissan

PartModel

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);
        }
    }
}

PartsRepository.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) { }
    }
}

ModelsRepository.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),我可以在单个事务中执行多表删除,这样可以确保从中删除数据。这两个表都是ModelPartModel

当前,我的代码如下(此方法有效,但请注意,我在两个存储库调用上都进行了提交,这有一种趋势,即一个事务可能会失败,但对数据库的更改仍将推送到另一个存储库调用上):

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();
    }
}

我将如何翻译它,以便对两个数据库删除命令都拥有一个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约束违规的问题。

我确实知道我要删除PartModelModel ,但是似乎不能将两个delete动作都纳入单个事务操作中。

感谢任何输入。

UPDATE

正如某些人在此处发布的那样,我已经更新了代码,以利用Microsoft推荐的Transactions。

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事件探查器或数据库拦截器来跟踪EF正在执行的查询。 有时,您需要在告诉EF删除依赖项时更加明确:跟踪应该使您很容易知道要删除的内容。 还要注意的另一件事是,EF假定FK关系默认为Cascade On Delete。 如果您尚未在配置中禁用此功能,并且EF不是生成数据库的用户,则不匹配会导致EF假定它需要发出的删除查询少于实际需要的删除查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM