public async Task <BookResultModel> CreateBook(string name, string description, string imageUrl, GenericComboBox author, DateTime?releaseDate, IEnumerable <GenericComboBox> categories) { BookResultModel result = new BookResultModel(); if (await this.dbContext.Books.AnyAsync(p => p.Name.ToLower().Trim() == name.ToLower().Trim())) { result.Success = false; result.Errors = new[] { "Book with this name already exist." }; return(result); } Book book = new Book { Id = Guid.NewGuid(), Name = name.Trim(), Description = description.Trim(), ImageUrl = imageUrl.Trim(), ReleaseDate = releaseDate, }; if (author != null && author.Id != default) { book.AuthorId = author.Id; } await this.dbContext.Books.AddAsync(book); if (categories != null && categories.Any()) { IEnumerable <Guid> categoryIds = categories.Where(x => x != null && x.Id != default).Select(x => x.Id); IEnumerable <Guid> categoriesInDB = await this.dbContext.Categories.Where(x => categoryIds.Contains(x.Id)).Select(x => x.Id).ToListAsync(); foreach (Guid categoryId in categoriesInDB) { XRefBookCategory xRefForInsert = new XRefBookCategory() { Id = Guid.NewGuid(), BookId = book.Id, CategoryId = categoryId }; this.dbContext.XRefBookCategories.Add(xRefForInsert); } } await this.dbContext.SaveChangesAsync(); result.Name = book.Name; result.Success = true; return(result); }
private async Task UpdateBookCategoriesAsync(IEnumerable <GenericComboBox> categories, Book book) { IEnumerable <XRefBookCategory> bookCategoriesInDb = book.BookCategories; IEnumerable <GenericComboBox> bookCategoriesForUpdate = categories.Where(x => x != null && x.Id != default); { // Insert if (bookCategoriesForUpdate != null && bookCategoriesForUpdate.Any()) { IEnumerable <Guid> booksForInsert = bookCategoriesForUpdate.Where(x => bookCategoriesInDb != null && bookCategoriesInDb.Any() && !bookCategoriesInDb.Select(y => y.CategoryId).Contains(x.Id)) .Select(x => x.Id); IEnumerable <Guid> dbObjsForUpdate = await this.dbContext.Categories.Where(x => booksForInsert.Contains(x.Id)).Select(x => x.Id).ToListAsync(); foreach (Guid categoryId in dbObjsForUpdate) { XRefBookCategory xRefForInsert = new XRefBookCategory() { Id = Guid.NewGuid(), BookId = book.Id, CategoryId = categoryId }; this.dbContext.XRefBookCategories.Add(xRefForInsert); } } } { // Delete if (bookCategoriesInDb != null && bookCategoriesInDb.Any()) { IEnumerable <XRefBookCategory> booksForDelete = bookCategoriesInDb.Where(x => bookCategoriesForUpdate != null && bookCategoriesForUpdate.Any() && !bookCategoriesForUpdate.Select(y => y.Id).Contains(x.CategoryId)); this.dbContext.XRefBookCategories.RemoveRange(booksForDelete); } } }