SqlBulkCopy 选项 KeepIdentity

SqlBulkCopy Options KeepIdentity

我正在尝试移动一个 table,我想保留来自源的标识值,但目标 Table 保留自动分配唯一标识符。目的地 Table 没有记录。我是否需要删除 Destination Table IDENTITY 设置才能正常工作?

// Create the SqlBulkCopy object using a connection string. 
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
                {


                    bulkCopy.DestinationTableName = "Log";
                    bulkCopy.ColumnMappings.Clear();
                    bulkCopy.ColumnMappings.Add("ID", "ID");
                    bulk
                    // How many Rows you want to insert at a time
                    //bulkCopy.BatchSize = 100000;
                    bulkCopy.BatchSize = 500;
                    // Set the timeout.
                    bulkCopy.BulkCopyTimeout = 0;

                    // Set up the event handler to notify after 4500 rows.
                    bulkCopy.SqlRowsCopied +=
                        new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
                    bulkCopy.NotifyAfter = 4500;


                    //(                  2093,000 row(s) affected)
                    //Always stopping at 2093,000
                    try
                    {
                        // INSERT only if row doesn't exist in the destination
                        //bulkCopy.InsertIfNotExists = true;
                        // Write from the source to the destination.
                        bulkCopy.WriteToServer(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        WriteLog("Log_10_11_18.txt", String.Format("Exception = {0}", ex.Message));
                        return false;
                    }

这对我有用...

    static void Main(string[] args) {

        //
        // Table definition:
        //
        // CREATE TABLE dbo.Test(Id INT IDENTITY(1, 1) NOT NULL, Content VARCHAR(MAX) NULL);
        //

        // Create some dummy data.
        var table = new DataTable();
        table.Columns.Add(new DataColumn("Id", typeof(System.Int32)));
        table.Columns.Add(new DataColumn("Content", typeof(System.String)));
        var row = table.NewRow();
        row["Id"] = 12345;
        row["Content"] = "Testing";
        table.Rows.Add(row);

        // Bulk copy it in.
        using (var connection = new SqlConnection(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=Sandbox;Integrated Security=SSPI"))
        using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, null)) {
            connection.Open();
            bulkCopy.DestinationTableName = "dbo.Test";
            bulkCopy.WriteToServer(table);
        };

        //
        // To check results:
        //
        // SELECT * FROM dbo.Test;
        //

    }