public void SetBatches(IEnumerable <Batch> batches) { if (batches == null || !batches.Any()) { return; } if (batches.Any(p => p.ProducerId != ProducerId)) { throw SheaftException.BadRequest("Une observation est liée au producteur, les lots doivent donc lui être liés."); } var existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>(); var newBatchIds = batches.Select(b => b.Id); var batchIdsToRemove = existingBatchIds.Except(newBatchIds); if (batchIdsToRemove.Any()) { RemoveBatches(Batches?.Where(b => batchIdsToRemove.Contains(b.BatchId)).Select(b => b.Batch).ToList()); } existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>(); var batchIdsToAdd = newBatchIds.Except(existingBatchIds); if (batchIdsToAdd.Any()) { AddBatches(batches.Where(b => batchIdsToAdd.Contains(b.Id)).ToList()); } Refresh(); }