public ActionResult CreateOrEdit(TimelineViewModel model) { if (ModelState.IsValid) { var db = AppUtilities.CurrentDbContext; Timeline entity; bool isCreate = model.Id == null; if (isCreate) { entity = new Timeline(); db.Timelines.Add(entity); entity.CreatorId = AppUtilities.GetCurrentUserIdRequired(); entity.CreationTimePoint = DateTime.UtcNow; } else { long idNonNull = (long)model.Id; entity = CommonUtilities.UniqueSingleOrDefault(db.Timelines.Where(e => e.Id == idNonNull)); if (entity == null) { model.Id = null; return View(model); } db.Entry(entity).State = System.Data.Entity.EntityState.Modified; // Only ID and non-updatable properties can change here, we simply use EntityToModel to reduce duplicate code and increase maintainability. EntityToModel(entity, model); } db.SaveChanges(); if (isCreate) { model.Id = entity.Id; } } return View(model); }
private static TimelineViewModel EntityToModel(Timeline entity, TimelineViewModel model) { model.CreationTimePoint = entity.CreationTimePoint; model.Id = entity.Id; model.Name = entity.Name; return model; }