ADO .net 2.0:调用DataAdapter.Update()后未更新PrimaryKey

时间:2009-11-25 17:21:49

标签: c# .net datatable ado

我在更新具有主键列的类型化DataTable时遇到了问题。 在我的代码中的某个时刻,我填充DataTables(其中一些有主键和外键列)然后我使用DataAdapters和Update()在一个事务中插入所有DataTable的数据。因为类型化的DataTables不允许PrimaryKey表为空,所以在那里插入一些整数值。在调用Update()之后,我希望用数据库PK更新PK列。

    public void UpdateMethod(DbTransaction transaction)
{
 DbDataAdapter dataAdapter = mDbProviderFactory.CreateDataAdapter();
 using (DbCommand insertCommand = CreateCommand())
 {
  insertCommand.Connection = mDbConnection;
  insertCommand.Transaction = transaction;
  dataAdapter.InsertCommand = insertCommand;
  dataAdapter.Update(dataTable);
 }

 // not sure if i need to do this:
 dataTable.AcceptChanges();

 // I would expect that databaseId is now the Id used in the database,
 // but it is the original Id which I set while creating the row entry
 databaseId = (int)dataTable.Rows[0]["Id"];
}

private DbCommand CreateCommand()
{
 // Make command object.
 DbCommand cmd = mDbProviderFactory.CreateCommand();

 // add command input parameters
 DbParameter parameter1 = mDbProviderFactory.CreateParameter();
 parameter1.ParameterName = mDatabaseParameterPrefix + "someColumn";
 parameter1.SourceColumn = "someColumn";
 parameter1.Size = 255;
 parameter1.DbType = DbType.String;

 // Output parameter
 DbParameter idParameter = mDbProviderFactory.CreateParameter();
 idParameter.ParameterName = mDatabaseParameterPrefix + "ID";
 idParameter.SourceColumn = "ID";
 idParameter.Direction = ParameterDirection.InputOutput;
 idParameter.DbType = DbType.Int32;

 // setup sql command
 cmd.Parameters.Add(parameter1);
 cmd.Parameters.Add(idParameter)
 cmd.CommandText = @"INSERT INTO [SomeTable] ([someColumn], ...) VALUES(@someColumn, ... ) SELECT CAST(SCOPE_IDENTITY() AS int) AS 'ID'";
 cmd.UpdatedRowSource = UpdateRowSource.Both;

 return cmd;
}

感谢任何提示!

2 个答案:

答案 0 :(得分:0)

当您填充数据表时设置了主键时,它不会覆盖已存在的行(但是,如果遇到匹配的主键,它可能会也可能不会更新非键元素,具体取决于您的loadoption设置为)

在填写之前,您必须先清除数据表,我相信。

答案 1 :(得分:0)

解决了它。问题是SQL语句:而不是

INSERT INTO [SomeTable]([someColumn],...)VALUES(@someColumn,...)SELECT CAST(SCOPE_IDENTITY()AS int)AS'ID'

必须是:

INSERT INTO [SomeTable]([someColumn],...)VALUES(@ someColumn,...)SELECT @ID = SCOPE_IDENTITY()

否则,主键的值不会分配给输出参数。