相关推荐recommended
Net8 EFCore Mysql 连接
作者:mmseoamin日期:2024-02-05

一、安装插件

  • Pomelo.EntityFrameworkCore.MySq (这里要选8.0.0以上版本低版本不支持.net8)

    二、配置数据库连接串

     appsettings.json 中配置数据库连接串

    "ConnectionStrings": {
      "Connection": "server=172.18.2.183;port=3306;database=students;uid=root;pwd=123456;CharSet=utf8"
    }

    三、添加实体类Student和数据库上下文

    新建 Entities 目录,在,根据表及字段,在目录下新建 Student 实体类,在类上加  [Table("student")] 表名、属性上加[Column("id")] 字段名等与表对应,代码如下:

    using System.ComponentModel.DataAnnotations.Schema;
    namespace Snai.Mysql.Entities
    {
        [Table("students")]
        public class Student
        {
            [Column("id")]
            public int ID { get; set; }
            [Column("name")]
            public string Name { get; set; }
        }
    }

    在根目录下加上 DataAccess 目录做为数据库操作目录,在该目录下加上 Base 目录做数据库上下文目录

    在 Base 目录下新建 SqlContext 上下文类,继承 DbContext 类,通过构造函数注入数据库连接,添加 DbSet 实体属性,代码如下:

    using Microsoft.EntityFrameworkCore;
    using Snai.Mysql.Entities;
    namespace Server.DataAccess.Base
    {
        public class SqlContext : DbContext
        {
            public SqlContext(DbContextOptions options)
                : base(options)
            { }
            public DbSet Student { get; set; }
        }
    }

    在DataAccess目录下创建Interface和Implement文件夹分别为数据库对应数据的接口和实现。

    接口定义:

    using Server.Mysql.Entities;
    namespace Server.DataAccess.Interface
    {
        public interface IStudentDao
        {
            //插入数据
            bool CreateStudent(Student student);
            //取全部记录
            IEnumerable GetStudents();
            //取某id记录
            Student GetStudentByID(int id);
            //根据id更新整条记录
            bool UpdateStudent(Student student);
            //根据id更新名称
            bool UpdateNameByID(int id, string name);
            //根据id删掉记录
            bool DeleteStudentByID(int id);
        }
    }

    实现:

    using Server.DataAccess.Base;
    using Server.DataAccess.Interface;
    using Server.Mysql.Entities;
    namespace Server.DataAccess.Implement
    {
        public class StudentDao : IStudentDao
        {
            private SqlContext _context;
            public StudentDao(SqlContext context)
            {
                _context = context;
            }
            //插入数据
            public bool CreateStudent(Student student)
            {
                _context.Student.Add(student);
                return _context.SaveChanges() > 0;
            }
            //取全部记录
            public IEnumerable GetStudents()
            {
                return _context.Student.ToList();
            }
            //取某id记录
            public Student? GetStudentByID(int id)
            {
                return _context.Student.SingleOrDefault(s => s.ID == id);
            }
            //根据id更新整条记录
            public bool UpdateStudent(Student student)
            {
                _context.Student.Update(student);
                return _context.SaveChanges() > 0;
            }
            //根据id更新名称
            public bool UpdateNameByID(int id, string name)
            {
                var state = false;
                var student = _context.Student.SingleOrDefault(s => s.ID == id);
                if (student != null)
                {
                    student.Name = name;
                    state = _context.SaveChanges() > 0;
                }
                return state;
            }
            //根据id删掉记录
            public bool DeleteStudentByID(int id)
            {
                var student = _context.Student.SingleOrDefault(s => s.ID == id);
                _context.Student.Remove(student);
                return _context.SaveChanges() > 0;
            }
        }
    }

    依赖注入

    在Program.cs中写入

    string? sqlConnection = builder.Configuration.GetConnectionString("Connection");
    if (sqlConnection != null) 
    {
        builder.Services.AddDbContext(options =>
        {
            var serverVersion = ServerVersion.AutoDetect(sqlConnection);  //mysql版本: {8.2.0-mysql}
            options.UseMySql(sqlConnection, serverVersion);
        });
    }
    builder.Services.AddScoped(); //对于同一个请求返回同一个实例

    设计表

    Net8 EFCore Mysql 连接,第1张

    Controller调用

    private IStudentDao _iStudentDao;
    public TestController(IStudentDao iStudentDao)  //构造函数中添加
    {
        _iStudentDao = iStudentDao;
    }
    //调用测试方法创建
    public void TestCreate()
    {
        Student student = new Student();
        student.ID = 1;
        student.Name = "在下没有钱";
        _iStudentDao.CreateStudent(student);
    }

    运行结果:

    Net8 EFCore Mysql 连接,第2张