简体   繁体   中英

Retrieving identity column after inserting data using SQLBulkCopy

I have a model:

public class A {
       public int NameID {get; set; }  //this represents the identity column in the database
       public string Name { get; set; }
       public string Value { get; set; }
}

I use an EnumerableDataReader which is an implementation of IDataReader which seems to be working just fine except it doesn't populate the identity PROPERTY: A.NameID after the INSERT happens. Here is my full code:

       var dr = new EnumerableDataReader<A>(lst);

        using (var bulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) {
            bulkCopy.ColumnMappings.Add(nameof(A.NameID), "nameid");
            bulkCopy.ColumnMappings.Add(nameof(A.Name), "name");
            bulkCopy.ColumnMappings.Add(nameof(A.Value, "value");
            bulkCopy.DestinationTableName = "NameTable";
            bulkCopy.WriteToServer(dr);
        }

At this point I am expecting "NameID" of all my objects to be populated with the identity column's value that is currently in the database for that row.

What am I doing wrong?

SqlBulkCopy only handles the copying of data, and is not an advanced DB Layer. As such it does not take responsibility for pulling back the IDs, and can't actually do it if it wanted to.

A pattern followed by most is to use SqlBulkCopy to insert to a staging temporary table, and then using INSERT INTO..OUTPUT Inserted.Id..SELECT * FROM #Tmp to get those rows in to your main table.

This will allow you to pull back your inserted IDs and update your models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM