public ActionResult Update(EmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                repository.UpdateEmployee(employee);
            }

            return Json(new[] { employee });
        }
        public ActionResult Create(EmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                employee.EmployeeID = repository.CreateEmployee(employee);
            }

            return Json(new[] { employee });
        }
        public ActionResult Update(EmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                repository.UpdateEmployee(employee);
            }

            return Json(new[] { employee }.ToDataSourceResult(new DataSourceRequest(), ModelState));
        }
        public void UpdateEmployee(EmployeeViewModel viewModel)
        {
            var employee = context.Employees.Include("Territories")
                .First(e => e.EmployeeID == viewModel.EmployeeID);
            viewModel.CopyToEmployee(employee);

            if (viewModel.Territories != null)
            {
                UpdateEmployeeTerritories(employee, viewModel);
            }

            context.SaveChanges();
        }
 public int CreateEmployee(EmployeeViewModel viewModel)
 {
     var employee = new Employee();
     viewModel.CopyToEmployee(employee);
     if (viewModel.Territories != null)
     {
         foreach (var territory in viewModel.Territories)
         {
             var employeeTerritory = territory.ToTerritory();
             context.Territories.Attach(employeeTerritory);
             employee.Territories.Add(employeeTerritory);
         }
     }
     context.Employees.AddObject(employee);
     context.SaveChanges();
     return employee.EmployeeID;
 }
        private void UpdateEmployeeTerritories(Employee employee, EmployeeViewModel viewModel)
        {
            var employeeTerritories = employee.Territories.ToList();
            foreach (var territory in employeeTerritories)
            {
                if (!viewModel.Territories.Any(t => t.TerritoryID == territory.TerritoryID))
                {
                    employee.Territories.Remove(territory);
                }
            }

            foreach (var territory in viewModel.Territories)
            {
                if (!employeeTerritories.Any(t => t.TerritoryID == territory.TerritoryID))
                {
                    var employeeTerritory = territory.ToTerritory();
                    context.Territories.Attach(employeeTerritory);
                    employee.Territories.Add(employeeTerritory);
                }
            }
        }