Net8 EFCore Mysql 连接

一、安装插件

  • 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<Student> 实体属性,代码如下:

复制代码
using Microsoft.EntityFrameworkCore;
using Snai.Mysql.Entities;

namespace Server.DataAccess.Base
{
    public class SqlContext : DbContext
    {
        public SqlContext(DbContextOptions<SqlContext> options)
            : base(options)
        { }

        public DbSet<Student> Student { get; set; }
    }
}

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

接口定义:

复制代码
using Server.Mysql.Entities;

namespace Server.DataAccess.Interface
{
    public interface IStudentDao
    {
        //插入数据
        bool CreateStudent(Student student);

        //取全部记录
        IEnumerable<Student> 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<Student> 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<SqlContext>(options =>
    {
        var serverVersion = ServerVersion.AutoDetect(sqlConnection);  //mysql版本: {8.2.0-mysql}
        options.UseMySql(sqlConnection, serverVersion);
    });
}
builder.Services.AddScoped<IStudentDao, StudentDao>(); //对于同一个请求返回同一个实例

设计表

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);
}

运行结果:

相关推荐
captain37633 分钟前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
心中有你02141 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
龙亘川1 小时前
综合素质评价业务建模:从过程性评价到成长档案全链路闭环
数据库·智慧城市·数据可视化
数据库小组1 小时前
NineData 实战教程:MySQL 5.5 数据迁移同步到 MySQL 8.0(跨版本升级)
数据库·mysql·mysql优化·数据库开发·数据库迁移·版本升级·数据复制
zhangjw342 小时前
1-5 PostgreSQL 数据类型全集:基础类型、字符串、数值、时间类型
数据库·postgresql
王中阳Go2 小时前
5.27 分钟干完后端和全部测试:一场三小时笔试的五个失分点,四个不在代码上
大数据·数据库·人工智能·后端·大语言模型
cnskylee2 小时前
【MySQL】麒麟V10 SP3系统安装MySQL-Commercial-8.0.46
数据库·mysql·adb
梦幻通灵2 小时前
修改MySQL数据库递增序列【持续更新】
数据库·mysql
liminla!3 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法
tongyiixiaohuang3 小时前
供应商主数据同步实战:从易快报到金蝶云星空的单一策略落地
java·网络·数据库