public async Task<Book> AddAsync(Book item) { Author existingAuthor = await _dbContext.Authors.FirstOrDefaultAsync(r => r.FirstName.ToUpper() == item.Author.FirstName.ToUpper() && r.LastName.ToUpper() == item.Author.LastName.ToUpper()); Category category = await _dbContext.Categories.FirstOrDefaultAsync(r => r.CategoryName.ToUpper() == item.Category.CategoryName.ToUpper()); if (existingAuthor != null && category != null) { item.Author = existingAuthor; item.Category = category; _dbContext.Books.Add(item); _dbContext.SaveChanges(); return item; } Author newAuthor = new Author() { FirstName = item.Author.FirstName, LastName = item.Author.LastName }; Category newCategory = new Category() { CategoryName = item.Category.CategoryName, CategoryDescription = item.Category.CategoryDescription, }; item.Author = newAuthor; item.Category = newCategory; _dbContext.Books.Add(item); await _dbContext.SaveChangesAsync(); return item; }
/// <summary> /// Add a book to current user selected by ID /// </summary> /// <param name="id"></param> /// <param name="item"></param> /// <returns></returns> public async Task<Book> AddBook(int id, Book item) { // var obj = _dbContext.Users var findedUser = await _dbContext.Users.FirstOrDefaultAsync(r => r.UserId == id); if (findedUser != null) { var book = await _dbContext.Books.FirstOrDefaultAsync(r => r.BookName == item.BookName); book.OwnersUsers.Add(findedUser); book.BooksLeft--; findedUser.Books.Add(book); _dbContext.Books.Attach(book); _dbContext.Users.Attach(findedUser); _dbContext.Entry(findedUser).State = EntityState.Modified;; _dbContext.Entry(book).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return book; } return null; }
public async Task<Book> UpdateAsync(Book item) { var updateValue = await _dbContext.Books.SingleOrDefaultAsync(r => r.BookName == item.BookName); if (updateValue != null) { updateValue.Author = item.Author; updateValue.BookName = item.BookName; updateValue.Category = item.Category; updateValue.ISBN = item.ISBN; updateValue.NumberOfPages = updateValue.NumberOfPages; updateValue.BookDescription = updateValue.BookDescription; updateValue.NumberOfPages = updateValue.NumberOfPages; updateValue.YearOfBook = updateValue.YearOfBook; updateValue.OriginalNameOfBook = updateValue.OriginalNameOfBook; _dbContext.Books.Attach(updateValue); _dbContext.Entry(updateValue).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return updateValue; } return null; }
public async Task<object> RemoveAsync(Book item) { _dbContext.Books.Remove(item); return await _dbContext.SaveChangesAsync(); }