Question

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.

  1. How I can get true values of Num when I'm adding a row?
  2. Is there smarter solution of "add rows" -> "perform something" -> "delete added rows" problem?

Thanks in advance.

Was it helpful?

Solution

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));

OTHER TIPS

I think the problem would be here:

row1 = datatable.Rows.Add(null, "Name1", File.ReadAllBytes(@"Images\photo1.jpg"));

Try to replace your statements with:

int i = 0;
datatable.Rows.Add(i++, "Name1", File.ReadAllBytes(@"Images\photo1.jpg"));
datatable.Rows.Add(i++, "Name2", File.ReadAllBytes(@"Images\photo2.jpg"));

And delete with

datatable.Rows[i].Delete();

Check it out these links on the MSDN:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top