have some problem with DataSets in c#, which represents structure and data of DB in sdf-file. I'm making some automatic test with DB, so I should add some rows in table, perform test and delete added rows from table.
Table schema:
Num - ID, autoincrementing, primary key
Name - string
Photo - Image (binary)
My code is:
adapter.Fill(set);
row1 = datatable.Rows.Add(null, "Name1", File.ReadAllBytes(@"Images\photo1.jpg"));
row2 = datatable.Rows.Add(null, "Name2", File.ReadAllBytes(@"Images\photo2.jpg"));
adapter.Update(set);
... perfoming test...
adapter.Fill(set);
row1.Delete();
row2.Delete();
adapter.Update(set);
But added rows are still in base. I tried use
datatable.Rows.Remove(row1);
datatable.Rows.Remove(row2);
but It cause no-such-row-exception because of wrong "Num" values in row1 and row2, which are different from actual autoincremented values in DB.
Thanks in advance.
I found a solution myself. First of all, I created a SQL Query in DB, which adds a row and return a Num value of new row:
INSERT INTO [Table] ([Name], [Photo]) VALUES (@Name, @Photo);
SELECT @@IDENTITY
I called it "InsertAndReturnIdentificator". And then I used inserting (with this new query) and deleting rows in adapter directly, without using a DataSet
private Nullable<decimal> row1;
private Nullable<decimal> row2;
row1 = adapter.InsertAndReturtIdentificator("Name1", File.ReadAllBytes(@"Images\Photo1.jpg")) as Nullable<decimal>;
row2 = adapter.InsertAndReturtIdentificator("Name2", File.ReadAllBytes(@"Images\Photo2.jpg")) as Nullable<decimal>;
... performing test ...
adapter.Delete(Decimal.ToInt32(row1.Value));
adapter.Delete(Decimal.ToInt32(row2.Value));