Steps:
- Create the context
- get the connection from the context
- Create the transaction (TransactionScope)
- Open the connection (will enlist the connection into the ambient transaction created in 3. and will prevent from closing the connection by the context)
- Do SaveChanges()
- Execute your stored procedure
- Commit the transaction
- 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();
}
}
}