C#/.net EF Core 链接 Mysql
- 1. 安装相关的 NuGet 的 DLL 包
- 2. 生成数据库的实体和 EF 的 DBcontext 对象
- 3. 在 Startup.cs 中添加配置
1. 安装相关的 NuGet 的 DLL 包
开发环境:Win10 + VS2019
Mysql 服务器版本:8.0.24
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Relational
Pomelo.EntityFrameworkCore.MySql
另两个一样
2. 生成数据库的实体和 EF 的 DBcontext 对象
在程序包控制台输入以下命令
Scaffold-DbContext "server=localhost;port=3306;user=user;password=password;database=student" -Provider "Pomelo.EntityFrameworkCore.MySql" -o Models -Context DBClassConext
3. 在 Startup.cs 中添加配置
将自动生成 DBClassConext 文件名替换下面的 YourDbContext
public void ConfigureServices(IServiceCollection services){services.AddMvc();services.AddSingleton<IStudentRepository, MockStudentRepository>();var connectionString &#61; "server&#61;localhost;user&#61;root;password&#61;root;database&#61;student";var serverVersion &#61; new MySqlServerVersion(new Version(8, 0, 24));services.AddDbContextPool<DBClassConext>(dbContextOptions &#61;> dbContextOptions.UseMySql(connectionString, serverVersion).EnableSensitiveDataLogging() .EnableDetailedErrors() );}
将 connectionString 放在配置文件中
private readonly IConfiguration _configuration;public Startup(IConfiguration configuration){_configuration &#61; configuration;}
var serverVersion &#61; new MySqlServerVersion(new Version(8, 0, 24));services.AddDbContextPool<DBClassConext>(dbContextOptions &#61;> dbContextOptions.UseMySql(_configuration.GetConnectionString("DBConnection"), serverVersion).EnableSensitiveDataLogging() .EnableDetailedErrors() );
在 appsettings.json 中添加
"ConnectionStrings": {"DBConnection": "server&#61;localhost;user&#61;root;password&#61;root;database&#61;student"}
参考网址:
[1]: https://blog.csdn.net/weixin_44146294/article/details/110949332
[2]: https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql