.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。