/// <summary> /// Only call this if the updated object is in a detached state. /// Otherwise EF is tracking the entity so no need to call update. /// </summary> /// <param name="project"></param> public void Update(Project project) { if (_uow.Entry(project).State == EntityState.Detached) { _uow.Set<Project>().Attach(project); _uow.Entry(project).State = EntityState.Modified; //foreach (var projectTeamMember in project.TeamMembers) //{ // _uow.Entry(projectTeamMember).State = EntityState.Added; //} //var currentTeam = await _uow.Set<ProjectTeamMember>().Where(ptm => ptm.ProjectId == project.Id).ToListAsync(); //foreach (var currentMember in currentTeam) //{ // currentMember.ProjectId = null; // _uow.Set<ProjectTeamMember>().Remove(currentMember); //} } }
public void Add(Project project) { _uow.Set<Project>().Add(project); }
public async Task<ActionResult> Edit(Project project, IEnumerable<string> selectedTeamMemberIds) { var projectToUpdate = (await repository.Get(p => p.Id == project.Id)).First(); if(selectedTeamMemberIds == null) { selectedTeamMemberIds = new string[0]; } var teamMemberIds = selectedTeamMemberIds as string[] ?? selectedTeamMemberIds.ToArray(); var selectedTeam = await personRepository.Find(p => teamMemberIds.Any(id => id == p.Id)); projectToUpdate.Name = project.Name; projectToUpdate.Code = project.Code; var currentTeam = new HashSet<string>(projectToUpdate.TeamMembers.Select(p => p.Id)); //if there are new members selected we must add them to the current team foreach (var selectedTeamMember in selectedTeam.Where(selectedTeamMember => currentTeam.All(personId => personId != selectedTeamMember.Id))) { projectToUpdate.TeamMembers.Add(selectedTeamMember); } //remove any current team member who is not apart of the selection foreach (var personId in currentTeam.Where(personId => selectedTeam.All(p => p.Id != personId))) { projectToUpdate.TeamMembers.Remove(projectToUpdate.TeamMembers.First(p => p.Id == personId)); } project.TeamMembers = projectToUpdate.TeamMembers; ModelState.Clear(); TryValidateModel(projectToUpdate); var vm = new ProjectViewModel { Project = project, CurrentUserId = CurrentUserId, PossibleProjectMembers = (await personRepository.Get()).ToList() }; if (!ModelState.IsValid) { return View(vm); } try { repository.Update(projectToUpdate); await uow.SaveChangesAsync(); } catch (DbEntityValidationException dbEx) { foreach (var entityValidationError in dbEx.EntityValidationErrors) { foreach (var validationError in entityValidationError.ValidationErrors) { ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage); } } return View(vm); } return RedirectToAction("Index"); }