public async Task <IActionResult> Create(CreateIllegalObjectViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest()); } try { var user = await _userManager.GetUserAsync(User); var illegalObject = new IllegalObject { Address = viewModel.Address, ApplicationUserId = user.Id, Description = viewModel.Description, Latitude = viewModel.Latitude, Longitude = viewModel.Longitude, StatusId = IllegalObjectStatuses.OnReview, CreatedAt = DateTime.Now }; _context.IllegalObjects.Add(illegalObject); _context.SaveChanges(); return(Ok()); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
/// <summary> /// Сохранение полученных объектов в базу данных /// </summary> private void SaveToDatabase(List <IllegalObjectViewModel> illegalObjects) { var statuses = _context.IllegalObjectStatuses.AsNoTracking().ToList(); foreach (var illegalObject in illegalObjects) { var newIllegalObjectStatus = statuses.FirstOrDefault(s => s.IllegalObjectStatusName == illegalObject.StatusName); if (newIllegalObjectStatus == null) { continue; } var illegalObjectInDb = _context.IllegalObjects.FirstOrDefault(x => x.NeagentId == illegalObject.NeagentId); if (illegalObjectInDb != null) { illegalObjectInDb.CreatedAt = illegalObject.CreatedAt ?? DateTime.Now; _context.IllegalObjects.Update(illegalObjectInDb); } else { var newIllegalObject = new IllegalObject { Name = illegalObject.Name, Description = illegalObject.Description, Address = illegalObject.Address, Infringement = illegalObject.Infringement, Latitude = illegalObject.Latitude, Longitude = illegalObject.Longitude, NeagentId = illegalObject.NeagentId, ResultsOfReview = illegalObject.ResultsOfReview, StatusId = newIllegalObjectStatus.IllegalObjectStatusId }; _context.IllegalObjects.Add(newIllegalObject); } _context.SaveChanges(); } }