当前位置: 首页 > news >正文

WPF【11_2】WPF实战-重构与美化(Entity Framework)-示例

示例:Entity Framework Core应用修改第10章(客户预约表例子)

--\Models\Customer.cs
public partial class Customer
{
    public Customer()
    {
        Appointments = new HashSet<Appointment>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string IdNnumber { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Appointment> Appointments { get; set; }
}


--\Models\Appointment.cs
public partial class Appointment
{
    public int Id { get; set; }
    public DateTime Time { get; set; }
    public int? CustomerId { get; set; }

    public virtual Customer Customer { get; set; }
}

--\Models\AppDbContext.cs
public partial class AppDbContext : DbContext
{
    public AppDbContext()
    {
    }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Appointment> Appointments { get; set; }
    public virtual DbSet<Customer> Customers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=course565;Persist Security Info=True;User ID=sa;Password=PaSSword12!;Pooling=False");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

        modelBuilder.Entity<Appointment>(entity =>
        {
            entity.Property(e => e.Time).HasColumnType("datetime");

            entity.HasOne(d => d.Customer)
                .WithMany(p => p.Appointments)
                .HasForeignKey(d => d.CustomerId)
                .HasConstraintName("FK_Appointments_Customers");
        });

        modelBuilder.Entity<Customer>(entity =>
        {
            entity.Property(e => e.Address)
                .IsRequired()
                .HasMaxLength(100)
                .IsFixedLength(true);

            entity.Property(e => e.IdNnumber)
                .IsRequired()
                .HasMaxLength(50)
                .IsFixedLength(true);

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50)
                .IsFixedLength(true);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

--\MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ShowCustomers();
    }

    private void ShowCustomers()
    {
        try
        {
            using (var db = new AppDbContext())
            {
                var customers = db.Customers.ToList();
                customerList.DisplayMemberPath = "Name";
                customerList.SelectedValuePath = "Id";
                customerList.ItemsSource = customers;
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

    private void customerList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            Customer selectedItem = customerList.SelectedItem as Customer;
            if (selectedItem == null)
            {
                appointmentList.ItemsSource = null;
                return;
            }
            NameTextBox.Text = selectedItem.Name;
            IdTextBox.Text = selectedItem.IdNnumber;
            AddressTextBox.Text = selectedItem.Address;

            using (var db = new AppDbContext())
            {
                var customerId = customerList.SelectedValue;
                var appointment = db.Appointments.Where(a => a.CustomerId == (int)customerId).ToList();

                appointmentList.DisplayMemberPath = "Time";
                appointmentList.SelectedValuePath = "Id";
                appointmentList.ItemsSource = appointment;
            }

        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
    }

    private void DeleteAppointment_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var appointmentId = appointmentList.SelectedValue;

            using (var db=new AppDbContext())
            {
                var appointmentToRmove = db.Appointments.Where(a => a.Id == (int)appointmentId).FirstOrDefault();

                db.Appointments.Remove(appointmentToRmove);

                db.SaveChanges();
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            customerList_SelectionChanged(null, null);
        }
    }

    private void DeleteCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var customerId = customerList.SelectedValue;
            using (var db = new AppDbContext())
            {
                var customerToRemove = db.Customers
                    .Include(c => c.Appointments)
                    .Where(c => c.Id == (int)customerId)
                    .FirstOrDefault();
                db.Customers.Remove(customerToRemove);
                db.SaveChanges();
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            ShowCustomers();
            customerList_SelectionChanged(null, null);
        }
    }

    private void AddCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var db = new AppDbContext())
            {
                var customer = new Customer()
                {
                    Name = NameTextBox.Text,
                    IdNnumber = IdTextBox.Text,
                    Address = AddressTextBox.Text
                };

                db.Customers.Add(customer);
                db.SaveChanges();
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            ShowCustomers();
        }
    }

    private void AddAppointment_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var db = new AppDbContext())
            {
                var appointment = new Appointment()
                {
                    Time = DateTime.Parse(AppointmentDatePicker.Text),
                    CustomerId = (int)customerList.SelectedValue
                };

                db.Appointments.Add(appointment);
                db.SaveChanges();
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            customerList_SelectionChanged(null, null);
        }
    }

    private void UpdateCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var db=new AppDbContext())
            {
                var customer = db.Customers.Where(c => c.Id == (int)customerList.SelectedValue).FirstOrDefault();

                customer.Name = NameTextBox.Text.Trim();
                customer.IdNnumber = IdTextBox.Text.Trim();
                customer.Address = AddressTextBox.Text.Trim();

                db.SaveChanges();
            }

        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            ShowCustomers();
        }
    }
}

http://www.xdnf.cn/news/668017.html

相关文章:

  • 数据仓库基础知识总结
  • Python-ArcGIS蒸散发组分解析与GPP估算技术
  • 数据中台(大数据平台)之数据仓库建设
  • LLM+RAG:文本分块处理策略
  • Apache DolphinScheduler存储系统详解| AI生成技术文档系列
  • Vue3进阶教程:1.初次了解vue
  • Mobaxterm解锁Docker
  • Docker Desktop for Windows 系统设置说明文档
  • DBCP连接池的使用方法和源码分析
  • PCB布局/走线
  • 2025年上半年第2批信息系统项目管理师论文真题解析与范文
  • 深入理解Java中的BigDecimal:高精度计算的核心工具
  • 第二批考更有利?软考高项两个批次考试难度对比分析!
  • 银河麒麟V10×R²AIN SUITE:用AI重构安全,以国产化生态定义智能未来
  • Ansible 配置Playbook文件格式、关键字和语法详解
  • 每日Prompt:古花卷
  • 探究Azure devops 流水线缓存
  • 详解MYSQL索引失效问题排查
  • 关于 Web 安全:6. 常见 CMS 开源系统风险点
  • 利用 `ngx_http_xslt_module` 实现 NGINX 的 XML → HTML 转换
  • 深度学习常用概念详解:从生活理解到技术原理
  • 新电脑配置五 jdk8,maven,idea,vscode
  • 单片机(MCU)的 IO 口静电、浪涌、电压异常等保护
  • OpenEuler-DNS多域服务器搭建
  • 基于 Node.js 的 Express 服务是什么?
  • div或button一些好看实用的 CSS 样式示例
  • Linux 下 C 语言实现工厂模式
  • 卓力达蚀刻工艺:精密制造的跨行业赋能者
  • day 33 python打卡
  • 【LeetCode 热题 100】打家劫舍 / 零钱兑换 / 单词拆分 / 乘积最大子数组 / 最长有效括号