1 安装程序包
- Microsoft.EntityFrameworkCore 5.0.10
- Pomelo.EntityFrameworkCore.MySql (5.0.0-alpha.2) 5.0.0
- Microsoft.Bcl.AsyncInterfaces 5.0.10
2 创建一个实体Person.cs
namespace xxxxxxxxxx
{
[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; }
}
}
3 创建一个数据库上下文MyDbContext.cs
,如下:
namespace xxxxxxxx
{
public class MyDbContext : DbContext
{
public DbSet<Person> People { get; set; }
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
}
}
4 配置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;"
}
}
5 在Startup.cs注册MySQL数据库上下文服务
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();
});
}
}
}
6 创建一个名为PeopleController
的控制器
namespace xxxxxxx.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 List<Person> GetfirstName(string mess)
{
var k= _dbContext.Set<Person>().Where(b => b.FirstName == mess).ToList();
return k;
}
/// <summary>
/// 读取所有
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult GetAll()
{
using (_dbContext)
{
var list = _dbContext.People.ToList();
return Ok(list);
}
}
}
}
数据库脚本
CREATE TABLE `people` (
`Id` int NOT NULL AUTO_INCREMENT,
`FirstName` varchar(50) NULL,
`LastName` varchar(50) NULL,
`CreatedAt` datetime NULL,
PRIMARY KEY (`Id`)
);
通过路径/api/控制器名/方法名,查看使用EF Core 5读取MySQL数据库操作是否成功,转自码友网的创建者-Rector