本文首發于《.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);
}
}
}
}
訪問地址:http://localhost:8166/api/people/create 來向MySQL資料庫寫入測驗資料,回傳結果為:

查看MySQL資料庫people表的結果:

說明使用EF Core 5成功連接到MySQL資料并寫入了期望的資料,
再訪問地址:http://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,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/281190.html
標籤:其他
上一篇:Mysql - 使用入門
下一篇:樹形結構的選單表設計與查詢

