public async Task <IActionResult> Post([FromBody] CountyPromotionEventViewModel countyPromotionEventVm) { if (countyPromotionEventVm == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } await ValidateCountyDay(countyPromotionEventVm.Date); var newItem = Mapper.Map <CountyPromotionEvent>(countyPromotionEventVm); newItem.SetCreation(UserName); _countyPromotionEventRepository.Add(newItem); if (!await UnitOfWork.SaveAsync()) { return(StatusCode(500, "保存时出错")); } var vm = Mapper.Map <CountyPromotionEventViewModel>(newItem); return(CreatedAtRoute("GetCountyPromotionEvent", new { id = vm.Id }, vm)); }
public async Task <IActionResult> Put(int id, [FromBody] CountyPromotionEventViewModel countyPromotionEventVm) { if (countyPromotionEventVm == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } await ValidateCountyDay(countyPromotionEventVm.Date); var dbItem = await _countyPromotionEventRepository.GetSingleAsync(x => x.Id == id, x => x.CountyPromotionEventBonuses); if (dbItem == null) { return(NotFound()); } var bonusVms = countyPromotionEventVm.CountyPromotionEventBonuses; countyPromotionEventVm.CountyPromotionEventBonuses = null; var bonuses = dbItem.CountyPromotionEventBonuses; dbItem.CountyPromotionEventBonuses = null; Mapper.Map(countyPromotionEventVm, dbItem); dbItem.SetModification(UserName); var toAddBonusVms = bonusVms.Where(x => x.Id == 0).ToList(); var toAddBonuses = Mapper.Map <List <CountyPromotionEventBonus> >(toAddBonusVms); foreach (var addBonus in toAddBonuses) { addBonus.SetCreation(UserName); _countyPromotionEventBonusRepository.Add(addBonus); } var bonusVmIds = bonusVms.Where(x => x.Id > 0).Select(x => x.Id).ToList(); var bonusIds = bonuses.Select(x => x.Id).ToList(); var toDeleteIds = bonusIds.Except(bonusVmIds); var toDeleteBonuses = bonuses.Where(x => toDeleteIds.Contains(x.Id)); _countyPromotionEventBonusRepository.DeleteRange(toDeleteBonuses); var toUpdateIds = bonusIds.Intersect(bonusVmIds); var toUpdateBonuses = bonuses.Where(x => toUpdateIds.Contains(x.Id)).ToList(); foreach (var bonus in toUpdateBonuses) { var bonusVm = bonusVms.SingleOrDefault(x => x.Id == bonus.Id); Mapper.Map(bonusVm, bonus); bonus.SetModification(UserName); _countyPromotionEventBonusRepository.Update(bonus); } dbItem.CountyPromotionEventBonuses = toAddBonuses.Concat(toUpdateBonuses).ToList(); _countyPromotionEventRepository.Update(dbItem); if (!await UnitOfWork.SaveAsync()) { return(StatusCode(500, "保存时出错")); } return(NoContent()); }