本文首发于《.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数据库写入/读取数据示例教程》源码托管地址:
https://gitee.com/codedefault/efcore-my-sqlsample
创立示例我的项目
应用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。
发表回复