简体   繁体   English

使用SQLBulkCopy插入数据后检索标识列

[英]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. 我使用一个EnumerableDataReader,它是IDataReader的一个实现,似乎运行良好,只是在插入发生后它没有填充身份PROPERTY:A.NameID。 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. 在这一点上,我希望所有对象的“ NameID”将使用该行当前在数据库中的标识列的值进行填充。

What am I doing wrong? 我究竟做错了什么?

SqlBulkCopy only handles the copying of data, and is not an advanced DB Layer. SqlBulkCopy仅处理数据的复制,而不是高级数据库层。 As such it does not take responsibility for pulling back the IDs, and can't actually do it if it wanted to. 因此,它不负责拉回ID,并且如果愿意的话实际上不能这样做。

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. 紧随其后的一种模式是使用SqlBulkCopy插入临时临时表,然后使用INSERT INTO..OUTPUT Inserted.Id..SELECT * FROM #Tmp将这些行放入主表。

This will allow you to pull back your inserted IDs and update your models. 这将允许您拉回插入的ID并更新模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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