From a78cff9e1fdc65cf64dac250c0770e354745ec40 Mon Sep 17 00:00:00 2001 From: Hamid Reza Mohammadi Date: Fri, 23 Oct 2020 12:14:59 +0330 Subject: [PATCH] #23 trying to impove import from sqlite by using transactions --- .../Services/Implementation/GanjoorService.cs | 38 +++++++++++-------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/RMuseum/Services/Implementation/GanjoorService.cs b/RMuseum/Services/Implementation/GanjoorService.cs index 8776b4f3..f3b6d8ab 100644 --- a/RMuseum/Services/Implementation/GanjoorService.cs +++ b/RMuseum/Services/Implementation/GanjoorService.cs @@ -32,14 +32,11 @@ namespace RMuseum.Services.Implementation using (SqliteConnection sqliteConnection = new SqliteConnection(connectionStringBuilder.ToString())) { await sqliteConnection.OpenAsync(); - IDbConnection dapper = sqliteConnection; - using (var sqlConnection = _context.Database.GetDbConnection()) { await sqlConnection.OpenAsync(); - using (var command = sqlConnection.CreateCommand()) - { + foreach (var poet in await dapper.QueryAsync("SELECT * FROM poet ORDER BY id")) { int poetId = (int)poet.id; @@ -47,25 +44,36 @@ namespace RMuseum.Services.Implementation { continue; } - command.CommandText = - $"INSERT INTO GanjoorPoets (Id, Name, Description) VALUES (${poet.id}, N'{poet.name}', N'{poet.description}')"; - await command.ExecuteNonQueryAsync(); - - - await _ImportSQLiteCatChildren(command, dapper, poetId, 0, poet.name); + + DbTransaction transaction = await sqlConnection.BeginTransactionAsync(); + try + { + using (var command = sqlConnection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = + $"INSERT INTO GanjoorPoets (Id, Name, Description) VALUES (${poet.id}, N'{poet.name}', N'{poet.description}')"; + await command.ExecuteNonQueryAsync(); + await _ImportSQLiteCatChildren(command, dapper, poetId, 0, poet.name); + await transaction.CommitAsync(); + } + } + catch (Exception exp2) + { + await transaction.RollbackAsync(); + return new RServiceResult(false, exp2.ToString()); + } + + } - } - } - - + } } catch(Exception exp) { return new RServiceResult(false, exp.ToString()); } - return new RServiceResult(true); }