public IHttpActionResult UpdateUser(int userId) { try { using (ReactNativeSampleEntities db = new ReactNativeSampleEntities()) { var user = db.Users.Find(userId); var form = HttpContext.Current.Request.Form; var selectedHobbies = JsonConvert.DeserializeObject <List <Hobbies> >(form.Get("selectedHobbies")); user.FirstName = form.Get("firstName"); user.LastName = form.Get("lastName"); user.Email = form.Get("email"); user.DOB = Convert.ToDateTime(form.Get("DOB")); user.Country = Convert.ToInt32(form.Get("country")); var previousHobbies = db.UserHobbiesMappings.Where(x => x.UserId == userId).ToList(); foreach (var hobby in previousHobbies) { db.UserHobbiesMappings.Remove(hobby); } for (int i = 0; i < selectedHobbies.Count(); i++) { UserHobbiesMapping userHobby = new UserHobbiesMapping(); userHobby.HobbyId = selectedHobbies[i].value; user.UserHobbiesMappings.Add(userHobby); } db.Entry(user).State = EntityState.Modified; return(Ok()); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later")); } }
public IHttpActionResult AddUser() { try { using (ReactNativeSampleEntities db = new ReactNativeSampleEntities()) { var form = HttpContext.Current.Request.Form; var hobbies = JsonConvert.DeserializeObject <List <Hobbies> >(form.Get("selectedHobbies")); User user = new User(); user.FirstName = form.Get("firstName"); user.LastName = form.Get("lastName"); user.Email = form.Get("email"); user.Country = Convert.ToInt32(form.Get("country")); user.Gender = form.Get("gender"); user.DOB = Convert.ToDateTime(form.Get("dob")); for (int i = 0; i < hobbies.Count(); i++) { UserHobbiesMapping hobby = new UserHobbiesMapping(); hobby.HobbyId = hobbies[i].value; user.UserHobbiesMappings.Add(hobby); } db.Users.Add(user); db.SaveChanges(); return(Ok()); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, "An error occcured, please try again later")); } }