Пример #1
0
        public DataTable ShredPrimitive(IEnumerable <T> source, DataTable table, LoadOption?options)
        {
            // Create a new table if the input table is null.
            table ??= new DataTable(typeof(T).Name);

            if (!table.Columns.Contains("Value"))
            {
                table.Columns.Add("Value", typeof(T));
            }

            // Enumerate the source sequence and load the scalar values into rows.
            table.BeginLoadData();
            using (IEnumerator <T> e = source.GetEnumerator())
            {
                Object[] values = new object[table.Columns.Count];
                while (e.MoveNext())
                {
                    values[table.Columns["Value"].Ordinal] = e.Current;

                    if (options != null)
                    {
                        table.LoadDataRow(values, (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(values, true);
                    }
                }
            }
            table.EndLoadData();

            // Return the table.
            return(table);
        }
Пример #2
0
        public DataTable ShredPrimitive(IEnumerable <T> source, DataTable table, LoadOption?options)
        {
            if (table == null)
            {
                table = new DataTable(typeof(T).Name);
            }

            if (!table.Columns.Contains("Value"))
            {
                table.Columns.Add("Value", typeof(T));
            }

            table.BeginLoadData();
            using (IEnumerator <T> e = source.GetEnumerator())
            {
                Object[] values = new object[table.Columns.Count];
                while (e.MoveNext())
                {
                    values[table.Columns["Value"].Ordinal] = e.Current;

                    if (options != null)
                    {
                        table.LoadDataRow(values, (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(values, true);
                    }
                }
            }
            table.EndLoadData();
            return(table);
        }
Пример #3
0
        /// <summary>
        /// Loads a DataTable from a sequence of objects.
        /// </summary>
        /// <param name="source">The sequence of objects to load into the DataTable.</param>
        /// <param name="table">The input table. The schema of the table must match that
        /// the type T.  If the table is null, a new table is created with a schema
        /// created from the public properties and fields of the type T.</param>
        /// <param name="options">Specifies how values from the source sequence will be applied to
        /// existing rows in the table.</param>
        /// <returns>A DataTable created from the source sequence.</returns>
        public DataTable Shred(IEnumerable <T> source, DataTable table, LoadOption?options)
        {
            // Load the table from the scalar sequence if T is a primitive type.
            if (typeof(T).IsPrimitive)
            {
                return(ShredPrimitive(source, table, options));
            }

            // Create a new table if the input table is null.
            table ??= new DataTable(typeof(T).Name);

            // Initialize the ordinal map and extend the table schema based on type T.
            table = ExtendTable(table, typeof(T));

            // Enumerate the source sequence and load the object values into rows.
            table.BeginLoadData();
            using (IEnumerator <T> e = source.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    if (options != null)
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), true);
                    }
                }
            }
            table.EndLoadData();

            // Return the table.
            return(table);
        }
 /// <summary>
 /// Copies the collection to a data table.
 /// </summary>
 /// <typeparam name="T">The type of object to be represented in the datatable.</typeparam>
 /// <param name="source">The source.</param>
 /// <param name="table">The table.</param>
 /// <param name="options">The options.</param>
 /// <returns>The value of <paramref name="table"/> modified to incorporate the structure of <typeparamref name="T"/> appended with data from <paramref name="source"/>.</returns>
 public static DataTable CopyToDataTable <T>(
     this IEnumerable <T> source,
     DataTable table,
     LoadOption?options)
 {
     return(new ObjectShredder <T>().Shred(source, table, options));
 }
Пример #5
0
        public DataTable Shred(IEnumerable <T> source, DataTable table, LoadOption?options)
        {
            if (typeof(T).IsPrimitive)
            {
                return(ShredPrimitive(source, table, options));
            }


            if (table == null)
            {
                table = new DataTable(typeof(T).Name);
            }

            // now see if need to extend datatable base on the type T + build ordinal map
            table = ExtendTable(table, typeof(T));

            table.BeginLoadData();
            using (IEnumerator <T> e = source.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    if (options != null)
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), true);
                    }
                }
            }
            table.EndLoadData();
            return(table);
        }
Пример #6
0
        public DataTable Shred(IEnumerable <T> source, DataTable table, LoadOption?options, bool useDisplayNames = false)
        {
            if (typeof(T).IsPrimitive)
            {
                table = ShredPrimitive(source, table, options);
            }

            if (table == null)
            {
                table = new DataTable(typeof(T).Name);
            }

            // now see if need to extend datatable base on the type T + build ordinal map
            table = ExtendTableBaseClassFirst(table, typeof(T));

            table.BeginLoadData();
            using (IEnumerator <T> e = source.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    if (options != null)
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), options.Value);
                    }
                    else
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), true);
                    }
                }
            }
            table.EndLoadData();
            if ((useDisplayNames))
            {
                RenameColumnsToDisplayName(table);
            }
            return(table);
        }
Пример #7
0
        private static DataTable LoadTableFromEnumerable <T>(IEnumerable <T> source, DataTable table, LoadOption?options, FillErrorEventHandler errorHandler)
            where T : DataRow
        {
            if (options.HasValue)
            {
                switch (options.Value)
                {
                case LoadOption.OverwriteChanges:
                case LoadOption.PreserveChanges:
                case LoadOption.Upsert:
                    break;

                default:
                    throw DataSetUtil.InvalidLoadOption(options.Value);
                }
            }


            using (IEnumerator <T> rows = source.GetEnumerator())
            {
                // need to get first row to create table
                if (!rows.MoveNext())
                {
                    return(table ?? throw DataSetUtil.InvalidOperation(SR.DataSetLinq_EmptyDataRowSource));
                }

                DataRow current;
                if (table == null)
                {
                    current = rows.Current;
                    if (current == null)
                    {
                        throw DataSetUtil.InvalidOperation(SR.DataSetLinq_NullDataRow);
                    }

                    table = new DataTable()
                    {
                        Locale = CultureInfo.CurrentCulture
                    };

                    // We do not copy the same properties that DataView.ToTable does.
                    // If user needs that functionality, use other CopyToDataTable overloads.
                    // The reasoning being, the IEnumerator<DataRow> can be sourced from
                    // different DataTable, so we just use the "Default" instead of resolving the difference.

                    foreach (DataColumn column in current.Table.Columns)
                    {
                        table.Columns.Add(column.ColumnName, column.DataType);
                    }
                }

                table.BeginLoadData();
                try
                {
                    do
                    {
                        current = rows.Current;
                        if (current == null)
                        {
                            continue;
                        }

                        object[] values = null;
                        try
                        {
                            // 'recoverable' error block
                            switch (current.RowState)
                            {
                            case DataRowState.Detached:
                                if (!current.HasVersion(DataRowVersion.Proposed))
                                {
                                    throw DataSetUtil.InvalidOperation(SR.DataSetLinq_CannotLoadDetachedRow);
                                }
                                goto case DataRowState.Added;

                            case DataRowState.Unchanged:
                            case DataRowState.Added:
                            case DataRowState.Modified:
                                values = current.ItemArray;
                                if (options.HasValue)
                                {
                                    table.LoadDataRow(values, options.Value);
                                }
                                else
                                {
                                    table.LoadDataRow(values, fAcceptChanges: true);
                                }
                                break;

                            case DataRowState.Deleted:
                                throw DataSetUtil.InvalidOperation(SR.DataSetLinq_CannotLoadDeletedRow);

                            default:
                                throw DataSetUtil.InvalidDataRowState(current.RowState);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!DataSetUtil.IsCatchableExceptionType(e))
                            {
                                throw;
                            }

                            FillErrorEventArgs fillError = null;
                            if (null != errorHandler)
                            {
                                fillError = new FillErrorEventArgs(table, values)
                                {
                                    Errors = e
                                };
                                errorHandler.Invoke(rows, fillError);
                            }
                            if (null == fillError)
                            {
                                throw;
                            }
                            else if (!fillError.Continue)
                            {
                                if (ReferenceEquals(fillError.Errors ?? e, e))
                                {
                                    // if user didn't change exception to throw (or set it to null)
                                    throw;
                                }
                                else
                                {
                                    // user may have changed exception to throw in handler
                                    throw fillError.Errors;
                                }
                            }
                        }
                    } while (rows.MoveNext());
                }
                finally
                {
                    table.EndLoadData();
                }
            }
            Debug.Assert(null != table, "null DataTable");
            return(table);
        }
Пример #8
0
 public static DataTable CopyToDataTable <T>(this IEnumerable <T> source, DataTable table, LoadOption?options)
 {
     return(new DataTableCreator <T>().CreateDataTable(source, table, options));
 }
Пример #9
0
 public static DataTable CopyToDataTable <T>(this IEnumerable <T> source, DataTable table, LoadOption?options)
 {
     return(new ObjectShredder(MetaDataHelper.GetPropertiesToSerialize).Shred(source, table, options));
 }
Пример #10
0
        /// <summary>
        /// Loads a DataTable from a sequence of objects.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="table">The input table. The schema of the table must match that
        /// the type T.  If the table is null, a new table is created with a schema
        /// created from the public properties and fields of the type T.</param>
        /// <param name="source">The sequence of objects to load into the DataTable.</param>
        /// <param name="bulkRuntimeTypeHandleMetadata">The bulk runtime type handle metadata.</param>
        /// <param name="options">Specifies how values from the source sequence will be applied to
        /// existing rows in the table.</param>
        /// <param name="outputIdentityDic">The output identity dic.</param>
        /// <param name="identifierOnly">if set to <c>true</c> [identifier only].</param>
        /// <returns>
        /// A DataTable created from the source sequence.
        /// </returns>
        private static DataTable Shred <TEntity>(this DataTable table, IEnumerable <TEntity> source, BulkRuntimeTypeHandleMetadata bulkRuntimeTypeHandleMetadata, LoadOption?options, Dictionary <int, TEntity> outputIdentityDic = null, bool identifierOnly = false) where TEntity : class
        {
            var counter = 0;

            // Enumerate the source sequence and load the object values into rows.
            table.BeginLoadData();
            using (var e = source.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    if (options != null)
                    {
                        table.LoadDataRow(ShredObject(bulkRuntimeTypeHandleMetadata, e.Current, counter, outputIdentityDic, identifierOnly), (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(ShredObject(bulkRuntimeTypeHandleMetadata, e.Current, counter, outputIdentityDic, identifierOnly), true);
                    }
                    counter++;
                }
            }
            table.EndLoadData();

            // Return the table.
            return(table);
        }
Пример #11
0
 /// <summary>
 /// 查询DataRow
 /// </summary>
 /// <param name="db">数据库名</param>
 /// <param name="sql">sql语句</param>
 /// <param name="param">参数</param>
 /// <param name="index">指定行索引</param>
 /// <param name="commandTimeout">命令超时时间</param>
 /// <param name="commandType">命令类型</param>
 /// <param name="loadOption">取值范围为 System.Data.LoadOption 枚举,指示如何中的现有行 System.Data.DataTable 实例内 DataSet 组合在一起共享相同的主键的传入行。</param>
 /// <returns>查询结果</returns>
 public static DataRow GetDataRow(string db, string sql, object param = null, int index = 0, int?commandTimeout = null, CommandType?commandType = null, LoadOption?loadOption = null)
 {
     using (DbHelper helper = new DbHelper(db))
     {
         return(helper.GetDataRow(sql, param, index, commandTimeout, commandType, loadOption));
     }
 }
Пример #12
0
 /// <summary>
 /// 查询DataSet
 /// </summary>
 /// <param name="db">数据库名</param>
 /// <param name="sql">sql语句</param>
 /// <param name="param">参数</param>
 /// <param name="commandTimeout">命令超时时间</param>
 /// <param name="commandType">命令类型</param>
 /// <param name="loadOption">取值范围为 System.Data.LoadOption 枚举,指示如何中的现有行 System.Data.DataTable 实例内 DataSet 组合在一起共享相同的主键的传入行。</param>
 /// <param name="tables">一个字符串,从该数组 Load 方法检索表名称信息。</param>
 /// <returns>查询结果</returns>
 public static DataSet GetDataSet(string db, string sql, object param = null, int?commandTimeout = null, CommandType?commandType = null, LoadOption?loadOption = null, params string[] tables)
 {
     using (DbHelper helper = new DbHelper(db))
     {
         return(helper.GetDataSet(sql, param, commandTimeout, commandType, loadOption, tables));
     }
 }
Пример #13
0
 /// <summary>
 /// 查询DataRow
 /// </summary>
 /// <param name="sql">sql语句</param>
 /// <param name="param">参数</param>
 /// <param name="index">指定行索引</param>
 /// <param name="commandTimeout">命令超时时间</param>
 /// <param name="commandType">命令类型</param>
 /// <param name="loadOption">取值范围为 System.Data.LoadOption 枚举,指示如何中的现有行 System.Data.DataTable 实例内 DataSet 组合在一起共享相同的主键的传入行。</param>
 /// <returns>查询结果</returns>
 public DataRow GetDataRow(string sql, object param = null, int index = 0, int?commandTimeout = null, CommandType?commandType = null, LoadOption?loadOption = null)
 {
     return(ExecuteWithTransaction(() =>
     {
         DataTable dataTable = GetDataTable(sql, param, commandTimeout, commandType, loadOption);
         if (dataTable != null && dataTable.Rows.Count > 0)
         {
             return dataTable.Rows[index];
         }
         return null;
     }));
 }
Пример #14
0
 /// <summary>
 /// 查询DataTable
 /// </summary>
 /// <param name="sql">sql语句</param>
 /// <param name="param">参数</param>
 /// <param name="commandTimeout">命令超时时间</param>
 /// <param name="commandType">命令类型</param>
 /// <param name="loadOption">取值范围为 System.Data.LoadOption 枚举,指示如何中的现有行 System.Data.DataTable 实例内 DataSet 组合在一起共享相同的主键的传入行。</param>
 /// <returns>查询结果</returns>
 public DataTable GetDataTable(string sql, object param = null, int?commandTimeout = null, CommandType?commandType = null, LoadOption?loadOption = null)
 {
     return(ExecuteWithTransaction(() =>
     {
         DataTable dataTable = new DataTable();
         IDataReader reader = Connection.ExecuteReader(sql, param, IsBeginTransaction && Transaction != null ? Transaction : null, commandTimeout, commandType);
         dataTable.Load(reader, loadOption ?? LoadOption.PreserveChanges);
         return dataTable;
     }));
 }