0

我正在使用 SqlBulkCopy 类对我的数据库进行批量插入/更新。数据插入/更新后,我想用它做更多的逻辑。

目前,我的 IDataReader 混合了要插入和更新的记录。针对数据库的所有操作都正常工作。但是,数据写入后,IDataReader 对象不再有任何行。

有没有办法保留行,并为插入的记录自动生成唯一标识符字段?

这是我的代码片段:

    public IDataReader DoBulkCopy<T>(List<T> DataToInsert, string DestinationTableName)
    {
        var BulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString, SqlBulkCopyOptions.KeepNulls);
        BulkCopy.BulkCopyTimeout = 0;
        BulkCopy.BatchSize = 50;
        BulkCopy.DestinationTableName = DestinationTableName;

        IDataReader reader = DataToInsert.AsDataReader();
        BulkCopy.WriteToServer(reader);
        BulkCopy.Close();

        return reader;
    }

提前致谢。

4

1 回答 1

0

I have come to the conclusion after much research that this is not possible. I was able to come up with a work around. What I did was wrote the DateTime.Now() to a variable prior to executing the query. After the query executed, I did a select query for all records where the LastUpdated timestamp field as greater than the DateTime variable recorded before the insert/update.

Please note this works fine in my scenario because the data in this table is inserted/updated by this scheduler only. If this was an app where the data can come from multiple places or users, this approach would need to be rethought or adjusted.

于 2012-12-11T04:26:37.953 回答