Reputation: 25
I am trying to use a query to find the last ID (entry) in the table called ContributorUser in the database FPTContributorUsers and then add in a new entry thus assigning it the next available ID.
the below code allows me to add data to the table in the database however when I run it the ID (new entry to the table) shows as 0 and not 4. because I currently have three entries in my table
[HttpPost]
public ActionResult AddContributor(ContributorUsers AddCont)
{
if (AddCont.UserID == null)
{
throw new HttpException(404, "Please enter a valid RacfId");
}
else
{
FPTContributorUsers NewUser = new FPTContributorUsers();
NewUser.UserID = AddCont.UserID;
NewUser.ID = AddCont.ID;
db.ContributorUsers.Add(NewUser);
db.SaveChanges();
return RedirectToAction("index");
}
}
Upvotes: 0
Views: 727
Reputation: 3779
Have you thought about just making that the primary key and having it auto increment so you don't need to determine what it is yourself? That's usually the best way to go about handling actual ID's in my experience.
To do this in SQL Server follow these steps
To do this in MySQL follow these steps
As a note, if you do this you will need to update your EF model.
The other way to do it if you can't edit the database is to use MAX() for that column which will return the highest ID value, then just add one to it, no EF model updating required.
Upvotes: 2
Reputation: 4185
Try Reload() the DB Context after SaveChanges() before you call the NewUser.ID so that the context is up-to-date
Upvotes: 0
Reputation: 61
Try removing the "NewUser.ID = AddCont.ID" line and wait to get the NewUser.ID until after "db.SaveChanges()"
else
{
FPTContributorUsers NewUser = new FPTContributorUsers();
NewUser.UserID = AddCont.UserID;
db.ContributorUsers.Add(NewUser);
db.SaveChanges();
return RedirectToAction("index");
}
If the NewUser.ID property is an Identity Field in the database, it will not get populated until after the record is created during the SaveChanges() transaction commit.
Upvotes: 0