You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中DataTable插入SQL Server后无法同步数据库生成的主键至对应行的问题求助

C#中DataTable插入SQL Server后无法同步数据库生成的主键至对应行的问题求助

各位好,我最近碰到一个棘手的问题:我在C#里维护了一个DataTable,其中主键列我先用负数做临时的自增标识,等把数据插入到SQL Server数据库后,想把数据库自动生成的真实主键值同步回DataTable对应的行里,但试了各种方法都没成功。

我之前看到过一个说法,说DataTable会自动同步这个主键值,但实际测试完全不管用。我还自己给InsertCommand加了逻辑去获取SCOPE_IDENTITY(),代码如下:

using (SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, connection))
using (SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter))
{
    var primaryKeyColumn = dataTable.PrimaryKey[0];
    var primaryKey = primaryKeyColumn.ColumnName;

    adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
    adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
    adapter.InsertCommand = commandBuilder.GetInsertCommand();

    adapter.InsertCommand.CommandText += "; SET @Identity = SELECT CAST(SCOPE_IDENTITY() AS int);";
    
    var identityParameter = adapter.InsertCommand.CreateParameter();
    identityParameter.ParameterName = "@Identity";
    identityParameter.DbType = DbType.Int32;
    identityParameter.Direction = ParameterDirection.Output;
    identityParameter.SourceColumn = primaryKey;
    
    adapter.InsertCommand.Parameters.Add(identityParameter);

    //adapter.RowUpdated += Adapter_RowUpdated;

    // Update database with changes from DataTable
    adapter.Update(dataTable);
}

这段代码里我特意加了输出参数去捕获数据库生成的主键,也关联了对应的源列,但执行完adapter.Update(dataTable)之后,DataTable里的主键还是原来的负数,完全没更新。

除此之外,我还尝试了用Adapter_RowUpdated事件,前后换了十几种写法去处理主键的同步,比如在事件里手动把SCOPE_IDENTITY()的值赋值给行的主键列,但不管怎么调,结果都不对。我实在摸不着头脑,不知道自己哪里弄错了,有没有大佬能帮我排查下问题?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:37:59