private async Task <int> RunSqlTransactionWithNoSqlWriteAsync(DbContext sqlContext, int bookChanges, Func <Task <int> > callBaseSaveChangesAsync) { if (sqlContext.Database.CurrentTransaction != null) { throw new InvalidOperationException("You can't use the NoSqlBookUpdater if you are using transactions."); } var applier = new ApplyChangeToNoSql(sqlContext, _noSqlContext); using (var transaction = sqlContext.Database.BeginTransaction()) { var result = await callBaseSaveChangesAsync(); //Save the SQL changes await applier.UpdateNoSqlAsync(_bookChanges); //apply the book changes to the NoSql database var numNoSqlChanges = await _noSqlContext.SaveChangesAsync(); //And Save to NoSql database if (bookChanges != numNoSqlChanges) { throw new InvalidOperationException($"{bookChanges} books were changed in SQL, but the NoSQL changed {numNoSqlChanges}"); } transaction.Commit(); return(result); } }
//-------------------------------------------------------------- //private methods private int RunSqlTransactionWithNoSqlWrite(DbContext sqlContext, Func <int> callBaseSaveChanges) { if (sqlContext.Database.CurrentTransaction != null) { throw new InvalidOperationException("You can't use the NoSqlBookUpdater if you are using transactions."); } var applier = new ApplyChangeToNoSql(sqlContext, _noSqlContext); using (var transaction = sqlContext.Database.BeginTransaction()) { var result = callBaseSaveChanges(); //Save the SQL changes applier.UpdateNoSql(_bookChanges); //apply the book changes to the NoSql database _noSqlContext.SaveChanges(); //And Save to NoSql database transaction.Commit(); return(result); } }