コード例 #1
0
ファイル: UnitOfWork.cs プロジェクト: Pharsat/eafit.cqrs
        public async Task <int> SaveChangesAsync()
        {
            var rowsAffected = 0;

            _connection.Open();
            var transaction = _connection.BeginTransaction();

            try
            {
                while (ActionsQueue.Count > 0)
                {
                    EntityAction entityAction = ActionsQueue.Dequeue();

                    var dbArguments = _dataComparer.TransformPropertiesToDynamicParameters(entityAction.Changes);

                    switch (entityAction.EntityState)
                    {
                    case EntityState.Added:
                        if (entityAction.Entity is NotAutoIdentityEntity)
                        {
                            string insertSqlQuery = _sqlGeneratorBase.BuildAddNotAutoidentitySqlCommand(entityAction.Entity);
                            await _connection.ExecuteAsync(insertSqlQuery, dbArguments, transaction).ConfigureAwait(false);
                        }
                        else
                        {
                            string insertSqlQuery = _sqlGeneratorBase.BuildAddSqlCommand(entityAction.Entity);
                            var    entityAdded    = await _connection.QueryAsync <int>(insertSqlQuery, dbArguments, transaction).ConfigureAwait(false);

                            entityAction.Entity.Id = entityAdded.Single();
                        }
                        break;

                    case EntityState.Deleted:
                        string deleteSqlQuery = _sqlGeneratorBase.BuildDeleteSqlCommand(entityAction.Entity, entityAction.EntityTypeName);
                        rowsAffected += await _connection.ExecuteAsync(deleteSqlQuery, new { entityAction.Entity.Id }, transaction).ConfigureAwait(false);

                        break;

                    case EntityState.Modified:
                        dbArguments.Add(nameof(entityAction.Entity.Id), entityAction.Entity.Id);
                        string updateSqlQuery = _sqlGeneratorBase.BuildUpdateSqlCommand(entityAction.Entity, entityAction.Changes);
                        rowsAffected += await _connection.ExecuteAsync(updateSqlQuery, dbArguments, transaction).ConfigureAwait(false);

                        break;
                    }
                }
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
            }
            finally
            {
                transaction.Dispose();
            }
            return(rowsAffected);
        }