public ActionResult Create(PICViewModel viewModel) { try { DateTime endD = Convert.ToDateTime(viewModel.EndDate.ToString()); DateTime startD = Convert.ToDateTime(viewModel.StartDate.ToString()); int endYear = Convert.ToInt32(viewModel.EndDate.Year.ToString()); int startYear = Convert.ToInt32(viewModel.StartDate.Year.ToString()); int compareDate = DateTime.Compare(endD, startD); var locationModel = _locationService.GetAll(); var assetTypeModel = _assetTypeService.GetAll(); var userModel = applicationUserManager.Users.ToList(); ViewBag.locationViewModel = Mapper.Map <IEnumerable <Location>, IEnumerable <LocationViewModel> >(locationModel); ViewBag.userViewModel = Mapper.Map <IEnumerable <ApplicationUser>, IEnumerable <UserViewModel> >(userModel); ViewBag.assetTypeViewModel = Mapper.Map <IEnumerable <AssetType>, IEnumerable <AssetTypeViewModel> >(assetTypeModel); if (endYear < 1970 || startYear < 1970) { return(View(viewModel)); } if (compareDate <= 0) { ModelState.AddModelError("EndDate", "EndDate must have a date greater than StartDate"); return(View(viewModel)); } var locationId = viewModel.Area.Location.ID; var listArea = _areaService.GetAllByLocationId(locationId); foreach (var area in listArea.ToList()) { //get exist pic var pic = _PICService.GetByAreaIdAndAssetTypeId(area.ID, viewModel.AssetType.ID); if (pic != null) { pic.ApplicationUserID = viewModel.ApplicationUser.Id; pic.StartDate = viewModel.StartDate; pic.EndDate = viewModel.EndDate; pic.Active = true; _PICService.Update(pic); } else { //add new pic when no pic exist pic = new PIC() { ApplicationUserID = viewModel.ApplicationUser.Id, AreaID = area.ID, AssetTypeID = viewModel.AssetType.ID, StartDate = viewModel.StartDate, EndDate = viewModel.EndDate, Active = true }; _PICService.Add(pic); } } _PICService.SaveChanges(); SetAlert("Add PIC success", "success"); } catch (Exception) { SetAlert("Add PIC error", "error"); } return(RedirectToAction("Index")); }