.NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程

本文首发于《.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程》

前言

在.NET Core/.NET 5的应用程序开发,与其经常搭配的数据库可能是SQL Server。而将.NET Core/.NET 5应用程序与SQL Server数据库的ORM组件有微软官方提供的EF Core(Entity Framework Core),也有像SqlSugar这样的第三方ORM组件。EF Core连接SQL Server数据库微软官方就有比较详细的使用教程和文档。

本文将为大家分享的是在.NET Core/.NET 5应用程序中使用EF Core 5连接MySQL数据库的方法和示例。

本示例源码托管地址请至《.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程》查看。

创建示例项目

使用Visual Studio 2019(当然,如果你喜欢使用VS Code也是没有问题的,笔者还是更喜欢在Visual Studio编辑器中编写.NET代码)创建一个基于.NET 5的Web API示例项目,这里取名为MySQLSample

项目创建好后,删除其中自动生成的多余的文件,最终的结构如下:

安装依赖包

打开程序包管理工具,安装如下关于EF Core的依赖包:

  • Microsoft.EntityFrameworkCore
  • Pomelo.EntityFrameworkCore.MySql (5.0.0-alpha.2)
  • Microsoft.Bcl.AsyncInterfaces

请注意Pomelo.EntityFrameworkCore.MySql包的版本,安装包时请开启包含预览,如:

创建实体和数据库上下文

创建实体

创建一个实体Person.cs,并定义一些用于测试的属性,如下:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MySQLSample.Models
{
    [Table("people")]
    public class Person
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime CreatedAt { get; set; }
    }
}

创建数据库上下文

创建一个数据库上下文MyDbContext.cs,如下:

using Microsoft.EntityFrameworkCore;
using MySQLSample.Models;

namespace MySQLSample
{
    public class MyDbContext : DbContext
    {
        public DbSet<Person> People { get; set; }

        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {

        }
    }
}

数据表脚本

CREATE TABLE `people`  (
  `Id` int NOT NULL AUTO_INCREMENT,
  `FirstName` varchar(50) NULL,
  `LastName` varchar(50) NULL,
  `CreatedAt` datetime NULL,
  PRIMARY KEY (`Id`)
);

创建好的空数据表people如图:

配置appsettings.json

将MySQL数据连接字符串配置到appsettings.json配置文件中,如下:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "MySQL": "server=192.168.1.22;userid=root;password=xxxxxx;database=test;"
    }
}

Startup.cs注册

在Startup.cs注册MySQL数据库上下文服务,如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MySQLSample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MyDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

创建一个名为PeopleController的控制器,写入如下代码:

using Microsoft.AspNetCore.Mvc;
using MySQLSample.Models;
using System;
using System.Linq;

namespace MySQLSample.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class PeopleController : ControllerBase
    {
        private readonly MyDbContext _dbContext;
        public PeopleController(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Create()
        {
            var message = "";
            using (_dbContext)
            {
                var person = new Person
                {
                    FirstName = "Rector",
                    LastName = "Liu",
                    CreatedAt = DateTime.Now
                };
                _dbContext.People.Add(person);
                var i = _dbContext.SaveChanges();
                message = i > 0 ? "数据写入成功" : "数据写入失败";
            }
            return Ok(message);
        }

        /// <summary>
        /// 读取指定Id的数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetById(int id)
        {
            using (_dbContext)
            {
                var list = _dbContext.People.Find(id);
                return Ok(list);
            }
        }

        /// <summary>
        /// 读取所有
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAll()
        {
            using (_dbContext)
            {
                var list = _dbContext.People.ToList();
                return Ok(list);
            }
        }
    }
}

访问地址://localhost:8166/api/people/create 来向MySQL数据库写入测试数据,返回结果为:

查看MySQL数据库people表的结果:

说明使用EF Core 5成功连接到MySQL数据并写入了期望的数据。

再访问地址://localhost:8166/api/people/getall 查看使用EF Core 5读取MySQL数据库操作是否成功,结果如下:

到此,.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据的示例就大功告成了。

谢谢你的阅读,希望本文的.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据的示例对你有所帮助。

我是码友网的创建者-Rector。