0

I have the following situation:

An ASP.NET Ajax web application uses a DataTable to write data to a database. The table is very simple, containing an autoincrement id.

My question:

If multiple users now use the web application, could it be that the same primary key id is given to multiple DataRows (leading to an error, when inserting the data into the database (duplicate key))? If I am right, the id is already generated, when calling .NewRow().

Thanks for your help!

An example:

----------------------------------------------------------
|   ID (primary, autoincrement)   |   C1     |     C2    |
----------------------------------------------------------

DataTable dt = new DataTable(name);

DataReader dr = ...;

dt.Load(dr); // => Now the data table has the rows from the database, including column definitions.
DataRow dr = dt.NewRow();
// => Now dr["ID"] is already set.
2
  • A primary key must contain unique values. Commented Jul 21, 2016 at 10:33
  • And therefore this situation would lead to an exception, yes. Commented Jul 21, 2016 at 11:04

2 Answers 2

1

I could not get what you want but .NewRow() row will not add id automatically.

Just for e.g.

for(int i = 0; i < 10; i++)
    {
        row = table.NewRow();
        row["id"] = i;
        row["item"] = "item " + i.ToString();
        table.Rows.Add(row);
    }

Here you add new row by .NewRow() but values you have to provide(Unique Id==Primary key) in your case.

Sign up to request clarification or add additional context in comments.

2 Comments

If I consider this loop as n number of customers,logic seems right to me. :) [i know its just an example]
Thanks, I have added an example to my question. Indeed, the id is already set.
0

the ID is generated and use only once , so if you user mssql set auto increment to true , or in oracle database user sequence object or user GUID, this will prevent duplication ID in case of application fail , network late in multiple instances and or no singleton threading locations.

2 Comments

Does this mean that the NewRow() method gets the id directly from the database, or is the ID of the dataRow thrown away?
Data table is something like xml file ,just create new DataRow objects and add to DataTable. (add line to xml)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.