Exemple #1
0
        public T ExecuteCommand <T>(Func <IDbCommand, T> action)
        {
            AssertDisposed();

            var sw = Stopwatch.StartNew();

            try
            {
                _dataSession.EnsureConnection();

                var result = action(_command);

                LogCommand(sw.ElapsedMilliseconds);

                TriggerCallbacks();

                return(result);
            }
            catch (Exception exception)
            {
                throw this.CreateDataException(exception);
            }
            finally
            {
                _dataSession.ReleaseConnection();
                Dispose();
            }
        }
Exemple #2
0
        /// <summary>
        /// Copies all rows from the supplied <see cref="DataRow" /> array to a destination table.
        /// </summary>
        /// <param name="rows">An array of DataRow objects that will be copied to the destination table.</param>
        public void WriteToServer(DataRow[] rows)
        {
            AssertDisposed();

            try
            {
                _dataSession.EnsureConnection();

                using (var bulkCopy = Create())
                {
                    bulkCopy.WriteToServer(rows);
                    bulkCopy.Close();
                }
            }
            finally
            {
                _dataSession.ReleaseConnection();
                Dispose();
            }
        }
Exemple #3
0
        private TResult QueryFactory <TResult>(Func <TResult> query, bool supportCache)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            AssertDisposed();

            var watch = Stopwatch.StartNew();

            try
            {
                var cacheKey = CacheKey <TResult>(supportCache);
                if (GetCache(cacheKey) is TResult results)
                {
                    return(results);
                }

                _dataSession.EnsureConnection();

                results = query();

                TriggerCallbacks();

                SetCache(cacheKey, results);

                return(results);
            }
            catch (Exception ex)
            {
                watch.Stop();
                LogCommand(watch.Elapsed, ex);

                throw;
            }
            finally
            {
                // if catch block didn't already log
                if (watch.IsRunning)
                {
                    watch.Stop();
                    LogCommand(watch.Elapsed);
                }

                _dataSession.ReleaseConnection();
                Dispose();
            }
        }
        /// <summary>
        /// Executes the command against the connection and converts the results to <typeparamref name="TEntity" /> objects.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="factory">The <see langword="delegate" /> factory to convert the <see cref="T:System.Data.IDataReader" /> to <typeparamref name="TEntity" />.</param>
        /// <returns>
        /// An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <typeparamref name="TEntity" /> objects.
        /// </returns>
        public IEnumerable <TEntity> Query <TEntity>(Func <IDataReader, TEntity> factory)
            where TEntity : class
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            AssertDisposed();

            try
            {
                string cacheKey = CacheKey <TEntity>();
                if (GetCache(cacheKey) is List <TEntity> results)
                {
                    return(results);
                }

                results = new List <TEntity>();
                _dataSession.EnsureConnection();

                LogCommand();
                using (var reader = _command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var entity = factory(reader);
                        results.Add(entity);
                    }
                }

                TriggerCallbacks();

                SetCache(cacheKey, results);
                return(results);
            }
            finally
            {
                _dataSession.ReleaseConnection();
                Dispose();
            }
        }
Exemple #5
0
        private void Merge(DataTable tableData, Action <DbCommand> executeFactory)
        {
            var isBulk = _mergeDefinition.Mode == DataMergeMode.BulkCopy ||
                         (_mergeDefinition.Mode == DataMergeMode.Auto && tableData.Rows.Count > 1000);

            // Step 1, validate definition
            if (!Validate(_mergeDefinition, isBulk))
            {
                return;
            }

            try
            {
                _dataSession.EnsureConnection();

                var sqlConnection = _dataSession.Connection as SqlConnection;
                if (sqlConnection == null)
                {
                    throw new InvalidOperationException(
                              "Bulk-Copy only supported by SQL Server.  Make sure DataSession was create with a valid SqlConnection.");
                }

                var    sqlTransaction = _dataSession.Transaction as SqlTransaction;
                string mergeSql;

                if (isBulk)
                {
                    // Step 2, create temp table
                    string tableSql = DataMergeGenerator.BuildTable(_mergeDefinition);
                    using (var tableCommand = _dataSession.Connection.CreateCommand())
                    {
                        tableCommand.CommandText = tableSql;
                        tableCommand.CommandType = CommandType.Text;
                        tableCommand.Transaction = sqlTransaction;

                        tableCommand.ExecuteNonQuery();
                    }

                    // Step 3, bulk copy into temp table
                    using (var bulkCopy = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.Default, sqlTransaction))
                    {
                        bulkCopy.DestinationTableName = _mergeDefinition.TemporaryTable;
                        bulkCopy.BatchSize            = 1000;
                        foreach (var mergeColumn in _mergeDefinition.Columns.Where(c => !c.IsIgnored && c.CanBulkCopy))
                        {
                            bulkCopy.ColumnMappings.Add(mergeColumn.SourceColumn, mergeColumn.SourceColumn);
                        }

                        bulkCopy.WriteToServer(tableData);
                    }

                    // Step 4, merge sql
                    mergeSql = DataMergeGenerator.BuildMerge(_mergeDefinition);
                }
                else
                {
                    // build merge from data
                    mergeSql = DataMergeGenerator.BuildMerge(_mergeDefinition, tableData);
                }

                // run merge statement
                using (var mergeCommand = _dataSession.Connection.CreateCommand())
                {
                    mergeCommand.CommandText = mergeSql;
                    mergeCommand.CommandType = CommandType.Text;
                    mergeCommand.Transaction = sqlTransaction;

                    // run merge with factory
                    executeFactory(mergeCommand);
                }
            }
            finally
            {
                _dataSession.ReleaseConnection();
            }
        }