Reputation: 1705
I am generating user Id in this way from controller
long lastUserId = 0;
var userProfile = from m in db.UserProfiles select m;
userProfile = userProfile.Where(s => s.DbType == "OFFLINE");
foreach (var c in userProfile)
{
lastUserId = c.UserId;
}
if (lastUserId != 0)
{
lastUserId = lastUserId + 1;
}
else
{
lastUserId = 1000001;
}
When any two person register at same time and hit the controller I am getting the error of key violation now what to do?
Upvotes: 1
Views: 1270
Reputation: 15387
I will suggest use primary key on that column that have IDENTITY
, So you don't need to check.
if (lastUserId != 0)
{
lastUserId = lastUserId + 1;
}
else
{
lastUserId = 1000001;
}
It will automatically increase the value from the last one.
you can also define IDENTITY should be start from XYZ number and increase by 1 or as you want.
Each database support the IDENTITY feature.
Upvotes: 1
Reputation: 3914
Use a GUID for the Id or make the ID field Auto increment by taking BigInt at database and let Database to handle this.
Guid lastUserId;
var userProfile = from m in db.UserProfiles select m;
userProfile = userProfile.Where(s => s.DbType == "OFFLINE");
foreach (var c in userProfile)
{
lastUserId = c.UserId;
}
if (your condition)
{
lastUserId = new Guid();
}
Upvotes: 1
Reputation: 906
Use a GUID for the Id if generating the identifier in code
or
Use your database... if you must use long type then the identifier field should be an auto-incrementing primary key which creates the unique numeric value at insertion (BIGINT type value for SQL Server.)
Upvotes: 0