本文首发于《.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,并定义一些用于测试的属性,如下:

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.ComponentModel.DataAnnotations.Schema;
  4. namespace MySQLSample.Models
  5. {
  6. [Table("people")]
  7. public class Person
  8. {
  9. [Key]
  10. public int Id { get; set; }
  11. public string FirstName { get; set; }
  12. public string LastName { get; set; }
  13. public DateTime CreatedAt { get; set; }
  14. }
  15. }

创建一个数据库上下文MyDbContext.cs,如下:

  1. using Microsoft.EntityFrameworkCore;
  2. using MySQLSample.Models;
  3. namespace MySQLSample
  4. {
  5. public class MyDbContext : DbContext
  6. {
  7. public DbSet<Person> People { get; set; }
  8. public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
  9. {
  10. }
  11. }
  12. }
  1. CREATE TABLE `people` (
  2. `Id` int NOT NULL AUTO_INCREMENT,
  3. `FirstName` varchar(50) NULL,
  4. `LastName` varchar(50) NULL,
  5. `CreatedAt` datetime NULL,
  6. PRIMARY KEY (`Id`)
  7. );

创建好的空数据表people如图:

将MySQL数据连接字符串配置到appsettings.json配置文件中,如下:

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "AllowedHosts": "*",
  10. "ConnectionStrings": {
  11. "MySQL": "server=192.168.1.22;userid=root;password=xxxxxx;database=test;"
  12. }
  13. }

在Startup.cs注册MySQL数据库上下文服务,如下:

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Hosting;
  7. namespace MySQLSample
  8. {
  9. public class Startup
  10. {
  11. public Startup(IConfiguration configuration)
  12. {
  13. Configuration = configuration;
  14. }
  15. public IConfiguration Configuration { get; }
  16. public void ConfigureServices(IServiceCollection services)
  17. {
  18. services.AddDbContext<MyDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));
  19. services.AddControllers();
  20. }
  21. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  22. {
  23. if (env.IsDevelopment())
  24. {
  25. app.UseDeveloperExceptionPage();
  26. }
  27. app.UseRouting();
  28. app.UseAuthorization();
  29. app.UseEndpoints(endpoints =>
  30. {
  31. endpoints.MapControllers();
  32. });
  33. }
  34. }
  35. }

创建一个名为PeopleController的控制器,写入如下代码:

  1. using Microsoft.AspNetCore.Mvc;
  2. using MySQLSample.Models;
  3. using System;
  4. using System.Linq;
  5. namespace MySQLSample.Controllers
  6. {
  7. [ApiController]
  8. [Route("api/[controller]/[action]")]
  9. public class PeopleController : ControllerBase
  10. {
  11. private readonly MyDbContext _dbContext;
  12. public PeopleController(MyDbContext dbContext)
  13. {
  14. _dbContext = dbContext;
  15. }
  16. /// <summary>
  17. /// 创建
  18. /// </summary>
  19. /// <returns></returns>
  20. [HttpGet]
  21. public IActionResult Create()
  22. {
  23. var message = "";
  24. using (_dbContext)
  25. {
  26. var person = new Person
  27. {
  28. FirstName = "Rector",
  29. LastName = "Liu",
  30. CreatedAt = DateTime.Now
  31. };
  32. _dbContext.People.Add(person);
  33. var i = _dbContext.SaveChanges();
  34. message = i > 0 ? "数据写入成功" : "数据写入失败";
  35. }
  36. return Ok(message);
  37. }
  38. /// <summary>
  39. /// 读取指定Id的数据
  40. /// </summary>
  41. /// <returns></returns>
  42. [HttpGet]
  43. public IActionResult GetById(int id)
  44. {
  45. using (_dbContext)
  46. {
  47. var list = _dbContext.People.Find(id);
  48. return Ok(list);
  49. }
  50. }
  51. /// <summary>
  52. /// 读取所有
  53. /// </summary>
  54. /// <returns></returns>
  55. [HttpGet]
  56. public IActionResult GetAll()
  57. {
  58. using (_dbContext)
  59. {
  60. var list = _dbContext.People.ToList();
  61. return Ok(list);
  62. }
  63. }
  64. }
  65. }

访问地址: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。

版权声明:本文为bobositlife原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bobositlife/p/14713875.html