使用SaveChanges的相同事务从EF调用SP [英] Calling SP from EF using same transaction of SaveChanges

查看:73
本文介绍了使用SaveChanges的相同事务从EF调用SP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用objectContext SaveChanges方法(EntityFramework 5)的同一事务调用StoredProc吗?

Does someone knows how to call a StoredProc using the same transaction of an objectContext SaveChanges method (EntityFramework 5)?

目标是应用对象更改并调用在数据库上执行一些魔术"操作的存储的Proc,但是,如果出现问题(无论是SaveChanges还是SP执行),根本不会提交任何更改

The goal is to apply the objects changes and call a stored Proc that does some "magic" on the DB, but, if something goes wrong (either with the SaveChanges or with the SP execution) no changes would be committed at all.

推荐答案

步骤:

  1. 创建上下文
  2. 从上下文中获取连接
  3. 创建交易(TransactionScope)
  4. 打开连接(将连接加入到在3中创建的环境事务中,并防止通过上下文关闭连接)
  5. 执行SaveChanges()
  6. 执行存储过程
  7. 提交交易
  8. 关闭连接

某些代码(MyContext是从DbContext派生的):

Some code (MyContext is derived from DbContext):

using (var ctx = new MyContext())
{
    using (var trx = new TransactionScope())
    {
        var connection = ((IObjectContextAdapter)ctx).ObjectContext.Connection;
        try
        {
            ctx.Entities.Add(new MyEntity() { Number = 123 });
            ctx.SaveChanges();

            ctx.Database.ExecuteSqlCommand("INSERT INTO MyEntities VALUES(300)");
            trx.Complete();
        }
        finally
        {
            connection.Close();
        }
    }
}

这篇关于使用SaveChanges的相同事务从EF调用SP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆