public ActionResult CreateOrEdit(UserViewModel model) { if (!ModelState.IsValid) { return View(model); } model.Name = AppUtilities.ProcessUsernameInput(model.Name, ModelState, "model.Name"); model.EmailAddress = AppUtilities.ProcessEmailAddressInput(model.EmailAddress, ModelState, "model.EmailAddress"); if (!ModelState.IsValid) { return View(model); } var db = AppUtilities.CurrentDbContext; bool create = model.Id == null; User entity1; if (create) { entity1 = new User(); ModelToEntityCommon(model, entity1); entity1.SecurityStamp = Guid.NewGuid(); entity1.CreationTimePoint = DateTime.UtcNow; db.Users.Add(entity1); } else { long entityId = (long)model.Id; entity1 = CommonUtilities.UniqueSingleOrDefault(from entity2 in db.Users where entity2.Id == entityId select entity2); if (entity1 == null) { model.Id = null; return View(model); } ModelToEntityCommon(model, entity1); } try { db.SaveChanges(); if (create) { model.Id = entity1.Id; } return RedirectToAction("Index"); } catch (DbUpdateException dbUpdateEx) { bool t = AppUtilities.HandleCreateOrUpdateOneUserException(dbUpdateEx, ModelState, "model.EmailAddress", "model.Name"); if (t) { throw dbUpdateEx; } } return View(model); }
private static User ModelToEntityCommon(UserViewModel model, User entity) { entity.NamePadded = model.Name; entity.EmailAddressPadded = model.EmailAddress; return entity; }