Esempio n. 1
0
        public static int ExecuteNonQueryBatch(IReadOnlyList <DbSqlCommand> sqlCommands, SqlConnection sqlConnection)
        {
            if (sqlCommands == null)
            {
                throw new ArgumentNullException(nameof(sqlCommands));
            }
            if (sqlConnection == null)
            {
                throw new ArgumentNullException(nameof(sqlConnection));
            }
            if (sqlCommands.Count == 0)
            {
                return(0);
            }

            var connectionsCount = sqlCommands.Count(c => c.Connection != null && c.Connection != sqlConnection);

            if (connectionsCount > 1)
            {
                throw new InvalidOperationException("All commands of a batch must use the same connection.");
            }

            var commandSet = new SqlCommandSet();

            commandSet.CommandTimeout = (int)TimeSpan.FromMinutes(5).TotalSeconds;

            foreach (var sqlCommand in sqlCommands)
            {
                commandSet.Append(sqlCommand.SqlCommand);
            }

            using (QueryTime.MeasureBatch(commandSet))
            {
                return(SqlCommands.ExecuteSqlCommand(() =>
                {
                    bool wasOpened = false;
                    if (sqlConnection.State != ConnectionState.Open)
                    {
                        sqlConnection.Open();
                        wasOpened = true;
                    }

                    try
                    {
                        commandSet.Connection = sqlConnection;
                        var changesCount = commandSet.ExecuteNonQuery();
                        return changesCount;
                    }
                    finally
                    {
                        if (wasOpened)
                        {
                            sqlConnection.Close();
                        }
                    }
                }));
            }
        }
Esempio n. 2
0
 public static QueryTime MeasureBatch(SqlCommandSet commandSet)
 {
     if (GlobalDbConfiguration.QueryLogger.DoWriteLog)
     {
         return(new QueryTime
         {
             sql = SqlCommands.GetSqlCommandText(commandSet.BatchCommand),
             stopwatch = Stopwatch.StartNew()
         });
     }
     else
     {
         return(new QueryTime()
         {
             stopwatch = Stopwatch.StartNew()
         });
     }
 }