If I'm in the middle of doing a bunch of updates within a transaction, and it throws an exception, I still want to log some information in a table in the same db context so I know what happened. I mistakenly thought, per this answer, that all I needed to do was create a new instance of the context and those db inserts would be separate from the transaction. However they too are being rolled back. And I'm not sure if it is because I am missing the new Database() wrapper, but it won't let me create this statement as it seems the Database class doesn't have a public constructor that allows this.
Then I saw this answer which likely explains why. And I could see that you may want to have multiple contexts included in the transaction.
So how can I, within a transaction, exclude some db inserts from that transaction so they are not rolled back?
This is an overly simplified example. In reality, the TransactionScope() is created at the top level in the controller, and the try{} occurs many method calls deep.
var contextA = new ContextA();
using (var scope = new TransactionScope())
{
// Log Errors in DB with new instance of same context
var contextAforLogging = new ContextA()
// Save entity in context A
contextA.Save(...);
//log step
contextAforLogging.Save(...);
contextAforLogging.SaveChanges();
// More updates to original entity in context A
contextA.Save(...);
//log step
contextAforLogging.Save(...);
contextAforLogging.SaveChanges();
// Commit tx-scope
scope.Complete();
}
catch (Exception ex) {
return....;
}
string[]and pass them all the way back up the chain and then log them outside of thetransaction, but that will take a decent amount of refactoring and complexity I was hoping to avoid if at all possible.TransactionScope.Suppress? It might be a lot cleaner if you isolated logging to a separate singleton or service.