当前位置: 首页 > 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();
        }
    }
}

相关文章:

  • Python深度挖掘:openpyxl与pandas高效数据处理实战
  • [问题解决]:Unable to find image ‘containrrr/watchtower:latest‘ locally
  • Python实现自动物体识别---基于深度学习的AI应用实战
  • Orpheus-TTS:AI文本转语音,免费好用的TTS系统
  • 吉林省CCPC与全国邀请赛(东北地区赛)游记
  • Visual Studio编译当前文件
  • 【运维自动化-标准运维】如何实现在不同步骤间传递参数
  • JDBC基本操作
  • 基于大语言模型的浏览器翻译插件
  • 一键下载智享 AI 直播(三代)!打造直播生态闭环,解锁流量增长新密码
  • JavaScript- 4.1 DOM-document对象
  • 如何设计高效的索引策略?
  • IoT/HCIP实验-1/物联网开发平台实验Part2(HCIP-IoT实验手册版)
  • Java 继承(下)
  • [java八股文][JavaSpring面试篇]SpringBoot
  • vue+threeJs 设置模型默认的旋转角度
  • some面试题2
  • 树莓派超全系列教程文档--(49)远程访问树莓派
  • 2.2.1 05年T3
  • 网络常识:网线和光纤的区别
  • 专门查大学的网站/百度游戏排行榜风云榜
  • 网站框架一般用什么做/微信管理系统平台
  • html5的网站/北京网络营销推广培训哪家好
  • 东莞哪家做网站好/外链代发软件
  • 项目大全网/前端seo是什么意思
  • 网页设计css代码大全风景/seo按照搜索引擎的