public async Task<BlResult<NodeModel>> SaveAsync(NodeModel nodeModel) { BlResult<NodeModel> blResult = new BlResult<NodeModel>(); try { if (nodeModel is null) { throw new ArgumentNullException(nameof(NodeModel)); } EnsureTransaction(); var fetchedEntity = await _nodeRepository.GetByIdAsync(nodeModel.Id); fetchedEntity = _mapper.Map(nodeModel, fetchedEntity); var attributesToDelete = fetchedEntity.NodeAttributes. Where(x => !nodeModel.NodeAttributes.Any(y => y.Id == x.Id)).ToList(); var attributesToAdd = nodeModel.NodeAttributes. Where(x => !fetchedEntity.NodeAttributes.Any(y => y.Id == x.Id)).Select(z => z.Id); if (nodeModel.Id > 0) { _nodeRepository.Edit(fetchedEntity); } else { fetchedEntity = _nodeRepository.Add(fetchedEntity); } await SaveChangesAsync(false); if (attributesToDelete != null && attributesToDelete.Count() > 0) { foreach (var item in attributesToDelete) { fetchedEntity.NodeAttributes.Remove(item); } await SaveChangesAsync(false); } if (attributesToAdd != null && attributesToAdd.Count() > 0) { await _nodeRepository.AddAttribuets(fetchedEntity, attributesToAdd); await SaveChangesAsync(false); } await SaveChangesAsync(); blResult.Success(_mapper.Map<NodeModel>(fetchedEntity)); } catch (ArgumentNullException) { blResult.Fail(BLErrorCodeTypeEnum.ArgumentIsNull); } catch (Exception ex) { blResult.Fail(BLErrorCodeTypeEnum.Unknown, ex.Message, ex); } return blResult; }