private void button1_Click(object sender, EventArgs e) { if (IsValid()) { using (var connection = new LibraryEntities()) { try { if (!isEditForm) { var book = new Books { InventoryNumber = textBoxInventoryNumber.Text, Title = textBoxTitle.Text, Author = textBoxAuthor.Text, Description = textBoxDescription.Text }; connection.Books.Add(book); connection.SaveChanges(); } else { var book = connection.Books.FirstOrDefault(b => b.Id == _bookId); if (book == null) { MessageBox.Show("An error occured while saving the book"); } else { book.InventoryNumber = textBoxInventoryNumber.Text; book.Author = textBoxAuthor.Text; book.Title = textBoxTitle.Text; book.Description = textBoxDescription.Text; connection.SaveChanges(); } } this.Dispose(); MessageBox.Show("Book was saved successfully"); } catch (Exception exception) { this.Dispose(); MessageBox.Show("An error occured while saving the book"); } } } }
private void DeleteBook(int bookId) { using (var context = new LibraryEntities()) { var book = context.Books.FirstOrDefault(b => b.Id == bookId); context.Books.Remove(book); context.SaveChanges(); } }