使用表适配器VB.net将数据集中的标识值插入表中

时间:2014-09-08 09:59:30

标签: vb.net adapter identity

有没有办法让表适配器插入我在插入新行时传递的数据集中的值?

我正在同步两个数据库,这很有用。

目前我正在尝试这样做,但它会自动增加并创建新的身份值。

    Dim dAdapterConstraints As New SqlClient.SqlDataAdapter("SELECT * FROM " + Tablename, _oConn)
    Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dAdapterConstraints)
    builder.QuotePrefix = "["
    builder.QuoteSuffix = "]"
    dAdapterConstraints.InsertCommand = builder.GetInsertCommand
    Dim insertcommandstr As String = dAdapterConstraints.InsertCommand.CommandText.Substring(0, dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1) + " [" + Primarykey + "], " + dAdapterConstraints.InsertCommand.CommandText.Substring(dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1, dAdapterConstraints.InsertCommand.CommandText.Length - (dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1))
    insertcommandstr = insertcommandstr.Replace("@p1", "@po1, @p1")
    dAdapterConstraints.InsertCommand.Parameters.Add("@po1", getdbtype(dataset.Tables(0).Columns(Primarykey).DataType), dataset.Tables(0).Columns(Primarykey).MaxLength, Primarykey)
    insertcommandstr = "SET IDENTITY_INSERT [" + Tablename + "] ON " + insertcommandstr + " SET IDENTITY_INSERT [" + Tablename + "] OFF"
    dAdapterConstraints.InsertCommand.CommandText = insertcommandstr
    dataset.EnforceConstraints = False

    ' opens connection 
    'fills dataset with results
    Try
        For Each row As DataRow In dataset.Tables(0).Rows
            row.SetAdded()
        Next
        dAdapterConstraints.Update(dataset)
    Catch ex As Exception
        _oConn.Close()
        MsgBox("Could not execute query on server database," + ex.ToString + ";Updating and inserting")
        Return False
    End Try

0 个答案:

没有答案