问题
I have a SQL Server Database with several tables. One of them has "ID" (primary key), "Name" and other columns that i won't mention here for sake of simplicity. "ID" column is auto increment, unique and when i add some row using "SQL Server management studio", "ID" column increments properly. Database is old and current auto increment is at 1244 or so.
Now, i have created a C# project that uses TYPED Dataset to work with data from database. My database starts empty, dataset is filled using table adapters, new rows are added using my program but there's a problem i have never stumbled upon so far: when my program adds new row to Dataset, then updates database (using table adapter), "ID" column in my database gets correct auto-incremented number (1245,1246 etc), BUT my "ID" column in dataset gets "-1", "-2" instead! What's the problem? How can i tell my dataset to use auto-increment seed specified by database instead generating it's own NEGATIVE (???) primary key numbers?
EDIT: I get and compare rows using this:
dsNames.tbNamesRow[] TMP = basedataset.tbNames.Select() as dsNames.tbNamesRow[];
foreach (dsNames.tbNamesRow row in TMP)
{
string Name = row.Name;
bool Found = Name == Search;
if (CompareDelegate != null)
Found = CompareDelegate(Name, Search);
if (Found)
{
int ID = row.ID;
break;
}
}
回答1:
My original comment was kind of incorrect, I assumed you were retrieving the value from the database and THAT dataset had incorrect values in it.
The way ADO.NET deals with preventing collisions with it's disconnected dataset, it assigns negative IDENTITY column values, because it wouldn't know a possible positive number that IS NOT a collision as it's disconnected. These (negative) values are unique in terms of that transaction.
When you try and commit your changes, the ADO.NET engine determines the proper SQL to produce the correct result.
来源:https://stackoverflow.com/questions/9379699/dataset-autoincrement-issue