Update A Table With Multiple Many To Many Relationship LINQ (c#) .Net (Dot Net)

Code Snippets 4 U
public async Task<Object> UpdateBookAsync(EditBookModel editBookModel)
        {
            // check if book id is provided
            if (editBookModel.Id < 0) return Task.FromResult(new { Message = "Failed" });
            // get the data of id from db
            var oldBook = _context.Bookss.Include(what => what.BooksCategories) // include the table containing bookId and categoryId
                .Include(wh => wh.BookAuthorss) //Include the other table containing bookId and authorId
                .FirstOrDefault(book => book.Id == editBookModel.Id);

            if (oldBook == null) return Task.FromResult(new { Message = "Failed" });
            if (editBookModel.Title != null) oldBook.Title = editBookModel.Title;
            if (editBookModel.Content != null) oldBook.Content = oldBook.Content;

            oldBook.BooksCategories.Clear(); // clear all the previous relations
            // Add new one received in model
            foreach (Category category in editBookModel.Categories)
            {
                oldBook.BooksCategories.Add(new BooksCategories()
                {
                    CategoryId = category.Id,
                    BookId = oldBook.Id
                });
            }

            // same as above
            oldBook.BookAuthorss.Clear();
            foreach (Authorss auth in editBookModel.Authors)
            {
                oldBook.BookAuthorss.Add(new BookAuthorss()
                {
                    AuthorId = auth.Id,
                    BookId = oldBook.Id
                });
            }

            _context.Bookss.Update(oldBook); // update the dbset
            int totalUpdates = await _context.SaveChangesAsync(); // update in db
            if (totalUpdates > 0) return Task.FromResult(new { Message = "Success" }); // respond if updated
            return Task.FromResult(new { Message = "Nothing To Update" }); // if no updates taken place
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

forty five + = 49