Steps:
- Create context
- get connection out of context
- Create a transaction (TransactionScope)
- Open the connection (the connection will close with the external transaction created in 3. and will not allow the connection to be closed by context)
- Save SaveChanges ()
- Running stored procedure
- Commit transaction
- Close connection
Some code (MyContext obtained 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(); } } }
source share