I have a table where i have one property called ID_client where is primary key. I have to search the max value from this property and do +1 to assign to a new client. I have the following code..
public int IDuser()
{
MembershipUserCollection iduser = Membership.GetAllUsers();
foreach (MembershipUser member in iduser)
{
UserEntity entity = new UserEntity();
entity.Username = member.UserName;
entity.Roles = "Users";
entity.Email = member.Email;
for (int i = 1; i <=iduser.Count; i++)
{
entity.ID_client = i;
}
_entities.Add(entity);
}
int maxID = _entities.Max(x => x.ID_client) +1;
return maxID;
}
If i create, for example, four users all be ok, 1, 2, 3 and 4. But if i delete third user, i have 1, 2 and 4 as ID_client, and the next new user, i want to assign 5, but this function returns me 4,not 5. Is like the function do a count + 1 instead max value +1.
Can someone help me?
Thanks.
The name you gave to your method does not reflect what the method is supposed to do. Give it a speaking name. I do not see what the inner loop is supposed to do. Drop it. Get the maximum id BEFORE adding new records. Maybe you want something like this
As others have already said, you could also use an auto increment column. This is safer in a multiuser environment.