public async Task <UpsertModel> UpsertStudent(UpsertMode mode, StudentViewModel model) { var upsert = new UpsertModel(); try { Activity activity; string title; System.Text.StringBuilder builder; // Apply changes Student = model.ParseAsEntity(Student); if (model.Enroll) { var term = db.Terms.FirstOrDefault(p => p.IsCurrentTerm); if (term != null) { Student.CurrentTermId = term.TermId; } } builder = new System.Text.StringBuilder(); if (model.StudentId == 0) { db.Students.Add(Student); title = "Student Added"; builder.AppendFormat("A Student record has been made for: {0} {1}", model.FirstName, model.LastName).AppendLine(); } else { db.Entry(Student).State = System.Data.Entity.EntityState.Modified; title = "Student Updated"; builder.Append("The following changes have been made to the Student details"); if (mode == UpsertMode.Admin) { builder.Append(" (by the Admin)"); } builder.Append(":").AppendLine(); } await db.SaveChangesAsync(); StudentId = Student.StudentId; if (model.Dp != null) { UploadDp(model.Dp); } // Save activity now so we have a StudentId. Not ideal, but hey activity = CreateActivity(title, builder.ToString()); activity.UserId = ServiceUserId; await db.SaveChangesAsync(); if (model.StudentId == 0) { upsert.ErrorMsg = "Student record created successfully"; } else { upsert.ErrorMsg = "Student record updated successfully"; } upsert.RecordId = Student.StudentId.ToString(); } catch (Exception ex) { upsert.ErrorMsg = ex.Message; //RecordException("Update Student Error", ex); } return(upsert); }