MainWindow.xaml.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using MongoDB.Bson;
  2. using MongoDB.Driver;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. namespace BookShelfMongoDB
  8. {
  9. public partial class MainWindow : Window
  10. {
  11. private BookStoreContext _context;
  12. public MainWindow()
  13. {
  14. InitializeComponent();
  15. _context = new BookStoreContext();
  16. Load();
  17. }
  18. private void Load()
  19. {
  20. BooksGrid.ItemsSource = _context.GetCollection<Book>("Book").Find(new BsonDocument()).ToList();
  21. }
  22. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  23. {
  24. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  25. {
  26. return;
  27. }
  28. Book book = new()
  29. {
  30. Name = TbPrice.Text,
  31. Price = price,
  32. Author = TbAuthor.Text,
  33. Category = TbCategory.Text,
  34. };
  35. _context.GetCollection<Book>("Book").InsertOne(book);
  36. Load();
  37. }
  38. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  39. {
  40. if (BooksGrid.SelectedItem is Book selectedBook)
  41. {
  42. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  43. {
  44. return;
  45. }
  46. selectedBook.Name = TbName.Text;
  47. selectedBook.Price = price;
  48. selectedBook.Author = TbAuthor.Text;
  49. selectedBook.Category = TbCategory.Text;
  50. _context.GetCollection<Book>("Book").ReplaceOne(x => x.Id == selectedBook.Id, selectedBook);
  51. Load();
  52. }
  53. }
  54. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  55. {
  56. if (BooksGrid.SelectedItem is Book selectedBook)
  57. {
  58. _context.GetCollection<Book>("Book").DeleteOne(x => x.Id == selectedBook.Id);
  59. Load();
  60. }
  61. }
  62. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  63. {
  64. if (BooksGrid.SelectedItem is Book selectedBook)
  65. {
  66. TbName.Text = selectedBook.Name;
  67. TbPrice.Text = selectedBook.Price.ToString();
  68. TbAuthor.Text = selectedBook.Author;
  69. TbCategory.Text = selectedBook.Category;
  70. }
  71. }
  72. }
  73. }