Exemplo n.º 1
0
        public static void BulkInsert <T>(this IEnumerable <T> getDatareader, string tableName, SqlConnection conn,
                                          SqlTransaction trans = null, bool createTableIfNotExist = false, bool dropTableIfExist = false)
        {
            var fieldsCreate = GetProperties <T>();

            if (dropTableIfExist)
            {
                conn.DropTable <T>(tableName, trans, true);
            }

            if (createTableIfNotExist)
            {
                conn.CreateTable <T>(tableName, false, trans);
            }

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, trans))
            {
                bulkCopy.DestinationTableName = $"[{tableName}]";
                bulkCopy.BulkCopyTimeout      = conn.ConnectionTimeout;
                bulkCopy.ColumnMappings.Clear();
                fieldsCreate.Select(e => bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(e.Item2, e.Item2)));

                using (GenericListDataReader <T> dataReader = new GenericListDataReader <T>(getDatareader, fieldsCreate.Select(s => s.Item1).ToList()))
                {
                    bulkCopy.WriteToServer(dataReader);
                }
            }
        }
Exemplo n.º 2
0
        public void InsertUsers(IEnumerable <User> users)
        {
            var connectionString = NitkaContext.CONNECTION_STRING;

            using (IDataReader reader = new GenericListDataReader <User>(users))
                using (SqlConnection connection = new SqlConnection(connectionString))
                    using (SqlBulkCopy bcp = new SqlBulkCopy(connection))
                    {
                        connection.Open();

                        bcp.DestinationTableName = "[Users]";

                        bcp.ColumnMappings.Add("Id", "Id");
                        bcp.ColumnMappings.Add("FirstName", "FirstName");
                        bcp.ColumnMappings.Add("LastName", "LastName");
                        bcp.ColumnMappings.Add("Number", "Number");
                        bcp.ColumnMappings.Add("Salary", "Salary");

                        bcp.WriteToServer(reader);
                    }
        }