1
\$\begingroup\$

I want to save NUnit local tests in a mysql database hosted in Amazon RDS, and

I'm wrapping up everything in a transaction like so :

using (var context = new StDbContext())
         {
            context.Database.Log = Console.Write;
            if (!context.Database.Connection.State.HasFlag(ConnectionState.Open))
            {
               context.Database.Connection.OpenAsync();
            }
            using (var transaction = context.Database.BeginTransaction())
            {
               try
               {
                  var unit_of_work = new UnitOfWork(context);
                  unit_of_work.Sessions.AddModelSession(Model, unit_of_work);
                  context.SaveChanges();

                  transaction.Commit();
               }
               catch (Exception ex)
               {
                  transaction.Rollback();
                  TestBaseCore.mNLogLoggerService.Error(ex.Message);
               }

            }
         }

Is there a better way of optimizing this code, in order to be sure that the connection or the current transaction is still open until all the data it is saved to the database? because when trying to save using this code to a local database everything works perfectly, but when saving to a database hosted by Amazon RDS, the code will crash with no exception.The only difference is the connection string

\$\endgroup\$
4
  • 1
    \$\begingroup\$ "when saving to a database hosted by Amazon RDS, the code will crash with no exception" This sounds like broken code, which is off topic here. \$\endgroup\$ – BCdotWEB May 24 '20 at 15:21
  • \$\begingroup\$ I'm more interested on a review for it. and possible code optimization. the broke code part I will handle. Maybe there is a better way of writing transactions and I'm missing something \$\endgroup\$ – mark02 May 24 '20 at 16:46
  • 1
    \$\begingroup\$ make your code full async or sync BeginTransactionAsync and SaveChangesAsync as you've opened an async connection OpenAsync();. Also, note that the sent data will be validated by SQL engine and not EF, so you should be specific in exceptions for better handling, you will need to include EF exceptions like DbUpdateException. \$\endgroup\$ – iSR5 May 25 '20 at 12:03
  • \$\begingroup\$ Why don't you await OpenAsync? Looks like only on a local db opening the connection is fast enough not to be awaited. \$\endgroup\$ – Gert Arnold May 25 '20 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.