public void SaveCustomerReviews(CustomerReview[] items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } var pkMap = new PrimaryKeyResolvingMap(); using (var repository = _repositoryFactory()) { using (var changeTracker = GetChangeTracker(repository)) { var alreadyExistEntities = repository.GetByIds(items.Where(m => !m.IsTransient()).Select(x => x.Id).ToArray()); foreach (var item in items) { var sourceEntity = AbstractTypeFactory <CustomerReviewEntity> .TryCreateInstance().FromModel(item, pkMap); var targetEntity = alreadyExistEntities.FirstOrDefault(x => x.Id == sourceEntity.Id); bool needRecountRating = targetEntity == null || targetEntity.Rating != sourceEntity.Rating; if (targetEntity != null) { changeTracker.Attach(targetEntity); sourceEntity.Patch(targetEntity); } else { repository.Add(sourceEntity); } if (needRecountRating) { var product = repository.GetProductById(sourceEntity.ProductId); product.Rating = _ratingService.Count(sourceEntity); } } CommitChanges(repository); pkMap.ResolvePrimaryKeys(); } } }