public async Task Update(PrintedEditionModel model) { PrintedEditionWithNestedObjects printedEdition = await _printedEditionRepository.GetWithNestedObjectsByIdAsync(model.Id); printedEdition.PrintedEdition = model.MapToEntity(printedEdition.PrintedEdition); List <int> authorIdsFromModel = model.AuthorModels.Select(item => item.Id).ToList(); List <int> authorIdsFromEntity = printedEdition.AuthorInBooks.Select(item => item.AuthorId).ToList(); List <AuthorInBook> listToRemove = printedEdition.AuthorInBooks.Where(item => !authorIdsFromModel.Contains(item.AuthorId)).ToList(); List <AuthorInBook> listToCreate = model.AuthorModels.Where(item => !authorIdsFromEntity.Contains(item.Id)).Select(item => new AuthorInBook { PrintedEditionId = printedEdition.PrintedEdition.Id, AuthorId = item.Id }).ToList(); await _printedEditionRepository.UpdateAsync(printedEdition.PrintedEdition); if (listToRemove.Any()) { await _authorInBookRepository.RemoveRangeAsync(listToRemove); } if (listToCreate.Any()) { await _authorInBookRepository.AddRangeAsync(listToCreate); } }
public async Task <PrintedEditionModel> CreateAsync(PrintedEditionModel model) { PrintedEdition printedEdition = model.MapToEntity(); await _printedEditionRepository.CreateAsync(printedEdition); List <AuthorInBook> authorInBooks = new List <AuthorInBook>(); if (model.AuthorModels.Any()) { authorInBooks = model.AuthorModels.Select(item => new AuthorInBook { PrintedEditionId = printedEdition.Id, AuthorId = item.Id }).ToList(); await _authorInBookRepository.AddRangeAsync(authorInBooks); } return(model); }