前言
在.NET Core/.NET 5的應(yīng)用程序開發(fā),與其經(jīng)常搭配的數(shù)據(jù)庫可能是SQL Server。而將.NET Core/.NET 5應(yīng)用程序與SQL Server數(shù)據(jù)庫的ORM組件有微軟官方提供的EF Core(Entity Framework Core),也有像SqlSugar這樣的第三方ORM組件。EF Core連接SQL Server數(shù)據(jù)庫微軟官方就有比較詳細的使用教程和文檔。
本文將為大家分享的是在.NET Core/.NET 5應(yīng)用程序中使用EF Core 5連接MySQL數(shù)據(jù)庫的方法和示例。
本示例《.NET 5/.NET Core使用EF Core 5(Entity Framework Core)連接MySQL數(shù)據(jù)庫寫入/讀取數(shù)據(jù)示例教程》源碼托管地址:
https://gitee.com/codedefault/efcore-my-sqlsample
創(chuàng)建示例項目
使用Visual Studio 2019(當然,如果你喜歡使用VS Code也是沒有問題的,筆者還是更喜歡在Visual Studio編輯器中編寫.NET代碼)創(chuàng)建一個基于.NET 5的Web API示例項目,這里取名為MySQLSample:

項目創(chuàng)建好后,刪除其中自動生成的多余的文件,最終的結(jié)構(gòu)如下:

安裝依賴包
打開程序包管理工具,安裝如下關(guān)于EF Core的依賴包:
- Microsoft.EntityFrameworkCore
- Pomelo.EntityFrameworkCore.MySql (5.0.0-alpha.2)
- Microsoft.Bcl.AsyncInterfaces



請注意
Pomelo.EntityFrameworkCore.MySql包的版本,安裝包時請開啟包含預(yù)覽,如:
image
創(chuàng)建實體和數(shù)據(jù)庫上下文
創(chuàng)建實體
創(chuàng)建一個實體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; }
}
}
創(chuàng)建數(shù)據(jù)庫上下文
創(chuàng)建一個數(shù)據(jù)庫上下文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)
{
}
}
}
數(shù)據(jù)表腳本
CREATE TABLE `people` (
`Id` int NOT NULL AUTO_INCREMENT,
`FirstName` varchar(50) NULL,
`LastName` varchar(50) NULL,
`CreatedAt` datetime NULL,
PRIMARY KEY (`Id`)
);
創(chuàng)建好的空數(shù)據(jù)表people如圖:

配置appsettings.json
將MySQL數(shù)據(jù)連接字符串配置到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數(shù)據(jù)庫上下文服務(wù),如下:
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();
});
}
}
}
創(chuàng)建一個名為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>
/// 創(chuàng)建
/// </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 ? "數(shù)據(jù)寫入成功" : "數(shù)據(jù)寫入失敗";
}
return Ok(message);
}
/// <summary>
/// 讀取指定Id的數(shù)據(jù)
/// </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);
}
}
}
}
訪問地址:http://localhost:8166/api/people/create 來向MySQL數(shù)據(jù)庫寫入測試數(shù)據(jù),返回結(jié)果為:

查看MySQL數(shù)據(jù)庫people表的結(jié)果:

說明使用EF Core 5成功連接到MySQL數(shù)據(jù)并寫入了期望的數(shù)據(jù)。
再訪問地址:http://localhost:8166/api/people/getall 查看使用EF Core 5讀取MySQL數(shù)據(jù)庫操作是否成功,結(jié)果如下:

到此,.NET 5/.NET Core使用EF Core 5(Entity Framework Core)連接MySQL數(shù)據(jù)庫寫入/讀取數(shù)據(jù)的示例就大功告成了。
謝謝你的閱讀,希望本文的.NET 5/.NET Core使用EF Core 5(Entity Framework Core)連接MySQL數(shù)據(jù)庫寫入/讀取數(shù)據(jù)的示例對你有所幫助。
我是碼友網(wǎng)的創(chuàng)建者-Rector。
