Visual Studio 2022连接mysql数据库3,利用Entity Framework Core技术实现一个表的CRUD

注意

关于VS中用ODBC连接mysql数据库,可参考我的这篇文章:https://www.cnblogs.com/ztn195/p/19144339

关于VS中用 ADO.NET来操作数据库,可参考我的这篇文章:https://www.cnblogs.com/ztn195/p/19148337

首先在VS 2022中可以新建两种C#桌面应用的项目:

image

Windows 窗体应用 (支持.NET 8.0) 创建的是现代、跨平台的新式项目。

Windows 窗体应用(.NET Framework) 创建的是传统、仅限Windows的旧式项目。
 
而想要用利用Entity Framework Core技术则必须采用支持.NET 8.0的Windows 窗体应用。


创建支持.NET 8.0的Windows 窗体应用

直接在VS2022中建就好了(上方图片中的第一个)。

 

安装依赖

安装下方图片的三个就好了

# 安装MySQL EF Core提供程序 Install-Package Pomelo.EntityFrameworkCore.MySql

image

 

具体代码

Student

查看代码
namespace 测试1.Models
{
    /// <summary>
    /// 学生实体类
    /// </summary>
    public class Student
    {
        /// <summary>
        /// 学生ID(主键,自增)
        /// </summary>
        public int Id { get; set; }
        
        /// <summary>
        /// 学生姓名
        /// </summary>
        public string Name { get; set; }
        
        /// <summary>
        /// 学生年龄
        /// </summary>
        public int Age { get; set; }
        
        /// <summary>
        /// 性别
        /// </summary>
        public string Gender { get; set; }
        
        /// <summary>
        /// 专业
        /// </summary>
        public string Major { get; set; }
        
        /// <summary>
        /// 入学日期
        /// </summary>
        public DateTime AdmissionDate { get; set; }
    }
}

StudentDbContext

查看代码
using Microsoft.EntityFrameworkCore;
using 测试1.Models;

namespace 测试1.DataAccess
{
    /// <summary>
    /// 学生数据库上下文
    /// </summary>
    public class StudentDbContext : DbContext
    {
        /// <summary>
        /// 学生表
        /// </summary>
        public DbSet<Student> Students { get; set; }
        
        /// <summary>
        /// 配置数据库连接
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionString = "server=localhost;user=root;password=;database=studentdb;";
            optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
        }
        
        /// <summary>
        /// 配置实体映射
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 指定表名
            modelBuilder.Entity<Student>().ToTable("student");
            
            // 配置主键
            modelBuilder.Entity<Student>().HasKey(s => s.Id);
            
            // 配置字段映射和属性
            modelBuilder.Entity<Student>()
                .Property(s => s.Name)
                .HasColumnName("name")
                .HasMaxLength(100)
                .IsRequired();
                
            modelBuilder.Entity<Student>()
                .Property(s => s.Age)
                .HasColumnName("age")
                .IsRequired();
                
            modelBuilder.Entity<Student>()
                .Property(s => s.Gender)
                .HasColumnName("gender")
                .HasMaxLength(10)
                .IsRequired();
                
            modelBuilder.Entity<Student>()
                .Property(s => s.Major)
                .HasColumnName("major")
                .HasMaxLength(100)
                .IsRequired();
                
            modelBuilder.Entity<Student>()
                .Property(s => s.AdmissionDate)
                .HasColumnName("admission_date")
                .HasColumnType("date")
                .IsRequired();
        }
    }
}

StudentRepository

查看代码
using 测试1.Models;
using System.Collections.Generic;
using System.Linq;

namespace 测试1.DataAccess
{
    /// <summary>
    /// 学生数据访问类
    /// </summary>
    public class StudentRepository
    {
        private readonly StudentDbContext _context;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public StudentRepository()
        {
            _context = new StudentDbContext();
        }
        
        /// <summary>
        /// 获取所有学生
        /// </summary>
        public List<Student> GetAllStudents()
        {
            return _context.Students.ToList();
        }
        
        /// <summary>
        /// 根据ID获取学生
        /// </summary>
        public Student GetStudentById(int id)
        {
            return _context.Students.FirstOrDefault(s => s.Id == id);
        }
        
        /// <summary>
        /// 添加学生
        /// </summary>
        public void AddStudent(Student student)
        {
            _context.Students.Add(student);
            _context.SaveChanges();
        }
        
        /// <summary>
        /// 更新学生信息
        /// </summary>
        public void UpdateStudent(Student student)
        {
            _context.Students.Update(student);
            _context.SaveChanges();
        }
        
        /// <summary>
        /// 删除学生
        /// </summary>
        public void DeleteStudent(int id)
        {
            var student = _context.Students.FirstOrDefault(s => s.Id == id);
            if (student != null)
            {
                _context.Students.Remove(student);
                _context.SaveChanges();
            }
        }
    }
}

StudentService

查看代码
using 测试1.DataAccess;
using 测试1.Models;
using System.Collections.Generic;
using System;

namespace 测试1.Business
{
    /// <summary>
    /// 学生业务逻辑类
    /// </summary>
    public class StudentService
    {
        private readonly StudentRepository _studentRepository;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public StudentService()
        {
            _studentRepository = new StudentRepository();
        }
        
        /// <summary>
        /// 获取所有学生
        /// </summary>
        public List<Student> GetAllStudents()
        {
            return _studentRepository.GetAllStudents();
        }
        
        /// <summary>
        /// 根据ID获取学生
        /// </summary>
        public Student GetStudentById(int id)
        {
            return _studentRepository.GetStudentById(id);
        }
        
        /// <summary>
        /// 添加学生
        /// </summary>
        public void AddStudent(Student student)
        {
            // 业务逻辑验证
            if (string.IsNullOrEmpty(student.Name))
                throw new ArgumentException("学生姓名不能为空");
            
            if (student.Age < 16 || student.Age > 30)
                throw new ArgumentException("学生年龄应在16-30岁之间");
            
            if (string.IsNullOrEmpty(student.Gender) || (student.Gender != "男" && student.Gender != "女"))
                throw new ArgumentException("性别只能是'男'或'女'");
            
            if (string.IsNullOrEmpty(student.Major))
                throw new ArgumentException("专业不能为空");
            
            _studentRepository.AddStudent(student);
        }
        
        /// <summary>
        /// 更新学生信息
        /// </summary>
        public void UpdateStudent(Student student)
        {
            // 业务逻辑验证
            if (string.IsNullOrEmpty(student.Name))
                throw new ArgumentException("学生姓名不能为空");
            
            if (student.Age < 16 || student.Age > 30)
                throw new ArgumentException("学生年龄应在16-30岁之间");
            
            if (string.IsNullOrEmpty(student.Gender) || (student.Gender != "男" && student.Gender != "女"))
                throw new ArgumentException("性别只能是'男'或'女'");
            
            if (string.IsNullOrEmpty(student.Major))
                throw new ArgumentException("专业不能为空");
            
            _studentRepository.UpdateStudent(student);
        }
        
        /// <summary>
        /// 删除学生
        /// </summary>
        public void DeleteStudent(int id)
        {
            _studentRepository.DeleteStudent(id);
        }
    }
}

 Form1

查看代码
using 测试1.Business;
using 测试1.Models;
using System;
using System.Windows.Forms;
using System.Data;

namespace 测试1
{
    public partial class Form1 : Form
    {
        private readonly StudentService _studentService;
        
        public Form1()
        {
            InitializeComponent();
            _studentService = new StudentService();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadStudentData();
        }
        
        private void LoadStudentData()
        {
            try
            {
                var students = _studentService.GetAllStudents();
                dataGridViewStudents.DataSource = students;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载数据失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void ClearInputs()
        {
            txtName.Text = "";
            txtAge.Text = "";
            txtGender.Text = "男";
            txtMajor.Text = "";
            dtpAdmissionDate.Value = DateTime.Now;
        }
        
        private void dataGridViewStudents_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewStudents.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridViewStudents.SelectedRows[0];
                txtName.Text = selectedRow.Cells["Id"].OwningColumn.DataPropertyName == "Id" ? 
                    selectedRow.Cells["NameColumn"].Value.ToString() : 
                    selectedRow.Cells["Name"].Value.ToString();
                txtAge.Text = selectedRow.Cells["Id"].OwningColumn.DataPropertyName == "Id" ? 
                    selectedRow.Cells["AgeColumn"].Value.ToString() : 
                    selectedRow.Cells["Age"].Value.ToString();
                txtGender.Text = selectedRow.Cells["Id"].OwningColumn.DataPropertyName == "Id" ? 
                    selectedRow.Cells["GenderColumn"].Value.ToString() : 
                    selectedRow.Cells["Gender"].Value.ToString();
                txtMajor.Text = selectedRow.Cells["Id"].OwningColumn.DataPropertyName == "Id" ? 
                    selectedRow.Cells["MajorColumn"].Value.ToString() : 
                    selectedRow.Cells["Major"].Value.ToString();
                dtpAdmissionDate.Value = selectedRow.Cells["Id"].OwningColumn.DataPropertyName == "Id" ? 
                    Convert.ToDateTime(selectedRow.Cells["AdmissionDateColumn"].Value) : 
                    Convert.ToDateTime(selectedRow.Cells["AdmissionDate"].Value);
            }
        }
        
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    MessageBox.Show("请输入学生姓名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtName.Focus();
                    return;
                }
                
                if (!int.TryParse(txtAge.Text, out int age) || age < 16 || age > 30)
                {
                    MessageBox.Show("请输入有效的年龄(16-30岁)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtAge.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(txtGender.Text) || (txtGender.Text != "男" && txtGender.Text != "女"))
                {
                    MessageBox.Show("性别只能是'男'或'女'", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtGender.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(txtMajor.Text))
                {
                    MessageBox.Show("请输入专业", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtMajor.Focus();
                    return;
                }
                
                var student = new Student
                {
                    Name = txtName.Text,
                    Age = age,
                    Gender = txtGender.Text,
                    Major = txtMajor.Text,
                    AdmissionDate = dtpAdmissionDate.Value
                };
                
                _studentService.AddStudent(student);
                LoadStudentData();
                ClearInputs();
                MessageBox.Show("添加成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewStudents.SelectedRows.Count > 0)
                {
                    var selectedRow = dataGridViewStudents.SelectedRows[0];
                    int studentId = (int)selectedRow.Cells["Id"].Value;
                    
                    // 验证输入
                    if (string.IsNullOrEmpty(txtName.Text))
                    {
                        MessageBox.Show("请输入学生姓名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtName.Focus();
                        return;
                    }
                    
                    if (!int.TryParse(txtAge.Text, out int age) || age < 16 || age > 30)
                    {
                        MessageBox.Show("请输入有效的年龄(16-30岁)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtAge.Focus();
                        return;
                    }
                    
                    if (string.IsNullOrEmpty(txtGender.Text) || (txtGender.Text != "男" && txtGender.Text != "女"))
                    {
                        MessageBox.Show("性别只能是'男'或'女'", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtGender.Focus();
                        return;
                    }
                    
                    if (string.IsNullOrEmpty(txtMajor.Text))
                    {
                        MessageBox.Show("请输入专业", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtMajor.Focus();
                        return;
                    }
                    
                    var student = new Student
                    {
                        Id = studentId,
                        Name = txtName.Text,
                        Age = age,
                        Gender = txtGender.Text,
                        Major = txtMajor.Text,
                        AdmissionDate = dtpAdmissionDate.Value
                    };
                    
                    _studentService.UpdateStudent(student);
                    LoadStudentData();
                    ClearInputs();
                    MessageBox.Show("更新成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("请先选择要更新的学生记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewStudents.SelectedRows.Count > 0)
                {
                    var selectedRow = dataGridViewStudents.SelectedRows[0];
                    var studentId = (int)selectedRow.Cells["Id"].Value;
                    
                    if (MessageBox.Show("确定要删除这条记录吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        _studentService.DeleteStudent(studentId);
                        LoadStudentData();
                        ClearInputs();
                        MessageBox.Show("删除成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的学生记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadStudentData();
        }
        
        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearInputs();
        }
    }
}

项目结构与运行结果

image

posted @ 2025-10-22 16:33  雨花阁  阅读(17)  评论(0)    收藏  举报