MainWindow.xaml.cs 2.8 KB

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