public async Task<ActionResult> Create(FormCreateViewModel model) { User user = new User(); user.ID = model.FirstName + new Random().Next(999999999).ToString() + model.LastName; user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Gender = model.Gender; context.Users.Add(user); var countryId = context.Countries.Where(m => m.Name == model.Country).Select(m => m.ID).FirstOrDefault(); UserCountry userCountry = new UserCountry(); userCountry.UserID = user.ID; userCountry.CountryID = countryId; context.UserCountries.Add(userCountry); UserDescription userDescription = new UserDescription(); userDescription.ID = user.ID + countryId; userDescription.UserID = user.ID; userDescription.Description = model.Description; context.UserDescriptions.Add(userDescription); foreach (var course in model.Courses) { UserCourse userCourse = new UserCourse(); if (course.Checked == true) { userCourse.UserID = user.ID; userCourse.CourseID = course.ID; userCourse.Checked = true; context.UserCourses.Add(userCourse); } } await context.SaveChangesAsync(); return RedirectToAction("Index", "FormExample"); }
public ActionResult Edit(FormCreateViewModel model) { User user = context.Users.Where(u => u.ID == model.UserID).FirstOrDefault(); TryUpdateModel(user, "", new string[] { "FirstName", "LastName", "Email", "Gender" }); UserDescription userDescription = context.UserDescriptions.Where(u => u.UserID == model.UserID).FirstOrDefault(); TryUpdateModel(userDescription, "", new string[] { "Description" }); UserCountry userCountry = context.UserCountries.Where(u => u.UserID == model.UserID).FirstOrDefault(); var countryId = context.Countries.Where(n => n.Name == model.Country).Select(i => i.ID).FirstOrDefault(); if (userCountry.CountryID != countryId) { if (userCountry != null) { context.UserCountries.Remove(userCountry); context.SaveChanges(); } UserCountry uCountry = new UserCountry(); uCountry.UserID = model.UserID; uCountry.CountryID = countryId; context.UserCountries.Add(uCountry); } var userCourses = context.UserCourses.Where(u => u.UserID == model.UserID).ToList(); List<string> uCourseIds = new List<string>(); foreach (var crId in userCourses) { uCourseIds.Add(crId.CourseID); } var newCourses = model.Courses.Where(x => x.Checked == true).ToList(); List<string> nCourseIds = new List<string>(); foreach (var crId in newCourses) { nCourseIds.Add(crId.ID); } if (!uCourseIds.SequenceEqual(nCourseIds)) { foreach (var crId in userCourses) { UserCourse userCourse = context.UserCourses.Where(x => x.UserID == model.UserID && x.CourseID == crId.CourseID).FirstOrDefault(); context.UserCourses.Remove(userCourse); context.SaveChanges(); } foreach (var course in model.Courses) { UserCourse userCourse = new UserCourse(); if (course.Checked == true) { userCourse.UserID = user.ID; userCourse.CourseID = course.ID; userCourse.Checked = true; context.UserCourses.Add(userCourse); } } } context.SaveChanges(); return RedirectToAction("Index", "FormExample"); }