Entity framework 在一个事务中调用多个服务方法

Entity framework 在一个事务中调用多个服务方法,entity-framework,entity-framework-6,transactionscope,Entity Framework,Entity Framework 6,Transactionscope,原谅我,我不擅长英语六级。如果我犯了一些错误。请帮我改正一下。谢谢 首先,我想在我的服务层中实现业务逻辑,如下所示 public class userService { void createWithCommit(User user) { MyEntityContext db= new MyEntityContext (); ... db.Users.add(user);//Add a new user entity

原谅我,我不擅长英语六级。如果我犯了一些错误。请帮我改正一下。谢谢

首先,我想在我的服务层中实现业务逻辑,如下所示

public class userService
{
    void createWithCommit(User user)
    {
        MyEntityContext db= new MyEntityContext ();
        ...
        db.Users.add(user);//Add a new user entity
        ....
        Work w = new Work();
        ... 
        db.Works.add(w);//Add a new work entity
        db.savechanges();//commit the changes which will insert 2 new record . one is user . another is work.
    }
}
class utilService
{
    void update(SomeClass cls)
    {
        using (var tran=new TransactionScope())
        {
          userService userSvr= new userService();
          userSvr.create();//this method already include a savechanges().
          jobService jobSvr= new jobService();
          jobSvr.update();//this method may include another savechanges().
          tran.Complete();//I don't why EF6 doesn't have the Commit method. just has the Complete method.
        }

    }
}
但在某些服务类中,我希望在一个事务中调用多个其他服务方法,如下所示

public class userService
{
    void createWithCommit(User user)
    {
        MyEntityContext db= new MyEntityContext ();
        ...
        db.Users.add(user);//Add a new user entity
        ....
        Work w = new Work();
        ... 
        db.Works.add(w);//Add a new work entity
        db.savechanges();//commit the changes which will insert 2 new record . one is user . another is work.
    }
}
class utilService
{
    void update(SomeClass cls)
    {
        using (var tran=new TransactionScope())
        {
          userService userSvr= new userService();
          userSvr.create();//this method already include a savechanges().
          jobService jobSvr= new jobService();
          jobSvr.update();//this method may include another savechanges().
          tran.Complete();//I don't why EF6 doesn't have the Commit method. just has the Complete method.
        }

    }
}
所以我可以在ASP.net MVC控制器中使用它,如下所示

class SomeController
{
    ActionResult index()
    {
        userService userSvr = new userService();
        userSvr.createWithCommit();

    }

    ActionResult util()
    {
        utilService utilSvr = new utilService ();
        userSvr.update(....);

    }
}
所以你们可以看到我的想法是我想在一个事务中包含多个服务方法。每个包含的服务方法可能包括也可能不包括代码
SaveChanges()
(这意味着事务已提交。对吗?)

你可以看到。在测试中,我尝试使用
TransactionScope
将多个服务方法包含到一个事务中。我指的是方法
utilService.update()
。但是调用
SaveChanges()之后,
TransactionScope
似乎不起作用。所以我的问题是:

有没有可能按照我的想法实施呢?如果有的话。我应该采用什么样的模式?(我听说UOW和存储库模式。它们是解决方案吗?谢谢。)

您需要实现工作单元模式以避免事务范围。
工作单元
存储库模式
是目前使用得相当广泛的东西

UoW公开公共方法
Commit
,以存储更改

通用存储库

public class GenericRepository<TEntity> where TEntity : class
{
    internal SchoolContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(SchoolContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}


一个工作单元模式将解决您的问题,这可能有助于您实施UOW谢谢Eldho,您能分享一些示例或阅读给我吗。这样我才能更好地理解它?我真的不知道如何开始。谢谢,谢谢,非常好。但是什么是
一般性的存储?请您在这里发布一些代码,谢谢。@Joe.wang请查看更新的答案,您可以在UOW模式中找到[此处]()的更多详细信息。我发现我们必须在UI表示层提交事务。因为控制器属于UI层,所以我想知道我们是否可以在UI层做到这一点。我的意思是在controller.@Joe.wang中调用unitOfWork.save()。这是基于msdn中的基本实现,通常这
save()
将位于数据层,通过数据传输对象,我们将数据从数据传输到业务是的,我也在msdn站点中找到了它+1.