MainWindow.xaml.cs 2.8 KB

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