public async Task <BookResultModel> UpdateBook(Guid id, string name, string description, string imageUrl, GenericComboBox author, DateTime?releaseDate, IEnumerable <GenericComboBox> categories) { BookResultModel result = new BookResultModel(); Book book = await this.dbContext.Books.Include(x => x.BookCategories).FirstOrDefaultAsync(p => p.Id == id); if (book == null) { result.Success = false; result.Errors = new[] { "Book with this Id not exist." }; return(result); } if (book.Name.ToLower().Trim() != name.ToLower().Trim() && await this.dbContext.Categories.AnyAsync(p => p.Name.ToLower().Trim() == name.ToLower().Trim() && p.Id != id)) { result.Success = false; result.Errors = new[] { "Book with this name already exist." }; return(result); } this.dbContext.Books.Attach(book); book.Name = name.Trim(); book.Description = description.Trim(); book.ImageUrl = imageUrl.Trim(); book.ReleaseDate = releaseDate; if (author != null && author.Id != default) { book.AuthorId = author.Id; } else { book.AuthorId = null; } await this.UpdateBookCategoriesAsync(categories, book); await this.dbContext.SaveChangesAsync(); result.Name = book.Name; result.Success = true; return(result); }
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); }