public CreateSelectResponse Create(CreateSelectRequest request) { var response = new CreateSelectResponse(); try { var select = request.MapTo<Select>(); DataContext.Selects.Add(select); if (request.ParentId != 0) { var parent = new Select { Id = request.ParentId }; DataContext.Selects.Attach(parent); select.Parent = parent; } if (request.ParentOptionId != 0) { var parentOption = new SelectOption { Id = request.ParentOptionId }; DataContext.SelectOptions.Attach(parentOption); select.ParentOption = parentOption; } DataContext.SaveChanges(); response.IsSuccess = true; response.Message = "Select has been added successfully"; } catch (DbUpdateException dbUpdateException) { response.Message = dbUpdateException.Message; } return response; }
public UpdateSelectResponse Update(UpdateSelectRequest request) { var response = new UpdateSelectResponse(); try { var select = DataContext.Selects.Where(p => p.Id == request.Id) .Include(p => p.Options) .Include(p => p.Parent) .Include(p => p.ParentOption) .Single(); DataContext.Entry(select).CurrentValues.SetValues(request); foreach (var option in select.Options.ToList()) { if (request.Options.All(c => c.Id != option.Id)) DataContext.SelectOptions.Remove(option); } foreach (var option in request.Options) { var existingOption = select.Options.SingleOrDefault(c => c.Id == option.Id); if (existingOption != null && option.Id != 0) { DataContext.Entry(existingOption).CurrentValues.SetValues(option); } else { var newOption = new SelectOption() { Text = option.Text, Value = option.Value }; select.Options.Add(newOption); } } if (request.ParentId != 0 && (select.Parent == null || select.Parent.Id != request.ParentId)) { var parent = new Select { Id = request.ParentId }; DataContext.Selects.Attach(parent); select.Parent = parent; var parentOption = new SelectOption { Id = request.ParentOptionId }; DataContext.SelectOptions.Attach(parentOption); select.ParentOption = parentOption; } else if (request.ParentId == 0) { select.Parent = null; select.ParentOption = null; } DataContext.SaveChanges(); response.IsSuccess = true; response.Message = "Select has been updated successfully"; } catch (DbUpdateException exception) { response.Message = exception.Message; } catch (ArgumentNullException exception) { response.Message = exception.Message; } catch (InvalidOperationException exception) { response.Message = exception.Message; } return response; }