Calling SP from EF using same transaction of SaveChanges

前端 未结 1 1004
说谎
说谎 2021-01-01 05:53

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

The goal is to apply the objects c

相关标签:
1条回答
  • 2021-01-01 06:27

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题