Calling SP from EF using same transaction of SaveChanges

谁说我不能喝 提交于 2019-11-30 10:15:20

Steps:

  1. Create the context
  2. get the connection from the context
  3. Create the transaction (TransactionScope)
  4. Open the connection (will enlist the connection into the ambient transaction created in 3. and will prevent from closing the connection by the context)
  5. Do SaveChanges()
  6. Execute your stored procedure
  7. Commit the transaction
  8. Close the connection

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!