In short, C# throws me “Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information”, while the table in question DOES have a Primary key (Identity, since it’s MSSQL).
My code is as following:
void loaddata()
{
try
{
DS = new DataSet();
sqladapt = new SqlDataAdapter("SELECT servicetag,name,defect,primkey FROM " + Properties.Settings.Default.DBtableLaptops + "", sqlcon);
sqladapt.FillSchema(DS, SchemaType.Source);
sqladapt.Fill(DS);
commandBuilder = new SqlCommandBuilder(sqladapt);
DT = DS.Tables[0];
Laptops_datagridview.DataSource = DT; //I'm using a datagridview to edit the data.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void savedata()
{
//Doesn't work yet.
try
{
sqladapt.Update(DS); // <-- Throws the aforementioned error.
sqladapt.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Data loading etc works fine, Adding new rows works aswell, and it saves it. But whenever i update or delete a row, it throws the error.
Primkey is my primary key, it’s an auto-incrementing integer.
I’ve been googling all day, but to no avail, the usual problem people have is that there is no primary key defined in the first place, but that’s not the case here.
Any input would be greatly appreciated, i’ve been shotgun-debugging for like 6 hours now.
EDIT:
The create statements for the table in question is as following:
CREATE TABLE [dbo].[laptopregistratieDB_laptops](
[Servicetag] [text] NOT NULL,
[Name] [text] NOT NULL,
[Defect] [bit] NOT NULL,
[primkey] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
You need to actually make your primkey column a primary key:
You can also specify such a constraint when creating a table:
or, if you want SQL Server to randomly generate the constraint name (not recommended, but some people do do it):
SQL Server will also randomly name the constraint if you apply a primary key constraint using the table designer (Right click next to the column you want to be primary key, choose “Set Primary Key”)
All of these options can also be used to specify multi-column primary keys, with the exception of the
[primkey] [int] IDENTITY(1,1) NOT NULL PRIMARY KEYvariant. (In the designer scenario, you have to highlight multiple rows before right clicking).