Skip to content
Advertisement

Using SQLAdapter and SQLCommandBuilder without a Primary Key

I’m exploring the use of SqlCommandBuilder alongside Adapter.Update() to synchronize a DataGridView with an SQL Database table.

I want to auto-generate SQL Update statements using SqlCommandBuilder.GetUpdateCommand(), however, it fails with “Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information“. This makes sense, because my table doesn’t have a primary key.

I cannot set the primary key on the source table, but I do have an identity column. I’d like to specify to the command builder which column to use as the primary key. There is such a feature on the DataTable class, but it seems to have no effect on the SqlCommandBuilder.

I tried the following:

But it seems that this information does not propagate to the SqlDataAdapter and SqlCommandBuilder because I still get the error.

Here’s the order I’ve tried:

Are there any solutions here at all, or do I have to specify the update and insert statements?

Advertisement

Answer

So, as pointed out by @PanagiotisKanavos, the SqlCommandBuilder does not support tables without primary keys, even if you set it in the DataTable object.

Therefore, I had no choice but write my own Command Builder.

To use it, you need to provide:

  • The SqlConnection to use
  • The Database (if not provided in the connection)
  • The SQLAdapter, with the Select Command already set (there’s a constructor for that)

How you use it:

Next, the full class code:

Using the following code to print the commands:

I get:

I have tested the insert, update and delete statements and they seem to all work!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement