MVC3 and Entity framework newbie here. I’m trying to write a controller that will handle both edits and creating new entries. Here is my code so far (most of it auto generated)
//POST: /License/Save
[HttpPost]
public string Save(LICENSE_USER license_user)
{
if (license_user.License_ID != 0)
{
if (ModelState.IsValid)
{
db.Entry(license_user).State = EntityState.Modified;
db.SaveChanges();
return "Save Complete";
}
}
else
{
if (ModelState.IsValid) {
db.LICENSE_USER.Add(license_user);
db.SaveChanges();
return "New License created - " + license_user.License_ID;
}
}
return "What's going on here?";
}
It works great for edits since I’m including the License_ID field in the POST. For new entries, however, I’m excluding the License_ID field and it defaults to 0. What’s the most elegant way to get the next License_ID field and updating the object with that field?
Make the
License_IDcolumn in your database a primary autoincrement key. This way you don’t need to set it manually when inserting a new entity. The database will take care.In your EDMX model the
StoreGeneratedPatternattribute must be set toIdentityfor this property.