AddOrUpdateClient.xaml.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Shapes;
  15. using WpfApp1.Models;
  16. namespace WpfApp1
  17. {
  18. /// <summary>
  19. /// Логика взаимодействия для AddOrUpdateClient.xaml
  20. /// </summary>
  21. public partial class AddOrUpdateClient : Window
  22. {
  23. ApplicationContext db = new ApplicationContext();
  24. Clients client;
  25. public AddOrUpdateClient()
  26. {
  27. InitializeComponent();
  28. LoadDatabase();
  29. client = new Clients();
  30. }
  31. public AddOrUpdateClient(int id)
  32. {
  33. InitializeComponent();
  34. LoadDatabase();
  35. client = db.Clients.Local.FirstOrDefault(x => x.ID == id);
  36. tbSurname.Text = client.Surname;
  37. tbName.Text = client.Name;
  38. tbPhoneNumber.Text = client.PhoneNumber;
  39. tbE_mail.Text = client.E_mail;
  40. }
  41. void LoadDatabase()
  42. {
  43. // гарантируем, что база данных создана
  44. db.Database.EnsureCreated();
  45. // загружаем данные из БД
  46. db.Clients.Load();
  47. }
  48. private void btnSave_Click(object sender, RoutedEventArgs e)
  49. {
  50. try
  51. {
  52. client.Surname = tbSurname.Text;
  53. client.Name = tbName.Text;
  54. client.PhoneNumber = tbPhoneNumber.Text;
  55. client.E_mail = tbE_mail.Text;
  56. if (client.ID == 0)
  57. {
  58. db.Clients.Add(client);
  59. }
  60. db.SaveChanges();
  61. MessageBox.Show("Клиент добавлен");
  62. Close();
  63. }
  64. catch (Exception ex)
  65. {
  66. MessageBox.Show(ex.Message);
  67. }
  68. }
  69. }
  70. }