准备
开发工具:Microsoft Visual Studio Community 2019
运行环境:.NET Core 3.1
SDK版本:3.1.419
数据库:MySQL 5.7.27
选择项目类型
如下:
选择版本
添加数据库连接
添加 NuGet包
EF包:Microsoft.EntityFrameworkCore
MySql包:Pomelo.EntityFrameworkCore.MySql
修改 appsettings.json 配置文件
"ConnectionStrings": {
"MySqlString": "Server=localhost;Port=3306;Database=demo;Uid=root;Pwd=123456;CharSet=utf8mb4;"
}
创建数据库上下文类 ForceDemoContext.cs
public class ForceDemoContext : DbContext
{
public ForceDemoContext(DbContextOptions<ForceDemoContext> options) : base(options)
{
}
public DbSet<ManageUser> ManageUser { get; set; }
}
修改 Startup.cs
services.AddDbContext<ForceDemoContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlString")));
使用示例
private readonly ForceDemoContext _dbContext;
public WeatherForecastController(ForceDemoContext dbContext)
{
_dbContext = dbContext;
}
public string GetTest()
{
var list = _dbContext.ManageUser.ToList();
return "123";
}
查看更多教程