C#/.net EF Core 链接 Mysql
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
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// 依赖注入
services.AddSingleton<IStudentRepository, MockStudentRepository>();
// Replace with your connection string.
var connectionString = "server=localhost;user=root;password=root;database=student";
// Replace with your server version and type.
// Use 'MariaDbServerVersion' for MariaDB.
// Alternatively, use 'ServerVersion.AutoDetect(connectionString)'.
// For common usages, see pull request #1233.
var serverVersion = new MySqlServerVersion(new Version(8, 0, 24));
// Replace 'YourDbContext' with the name of your own DbContext derived class.
services.AddDbContextPool<DBClassConext>(
dbContextOptions => dbContextOptions
.UseMySql(connectionString, serverVersion)
.EnableSensitiveDataLogging() // These two calls are optional but help
.EnableDetailedErrors() // with debugging (remove for production).
);
}
将 connectionString 放在配置文件中
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
var serverVersion = new MySqlServerVersion(new Version(8, 0, 24));
// Replace 'YourDbContext' with the name of your own DbContext derived class.
services.AddDbContextPool<DBClassConext>(
dbContextOptions => dbContextOptions
.UseMySql(_configuration.GetConnectionString("DBConnection"), serverVersion)
.EnableSensitiveDataLogging() // These two calls are optional but help
.EnableDetailedErrors() // with debugging (remove for production).
);
在 appsettings.json 中添加
"ConnectionStrings": {
"DBConnection": "server=localhost;user=root;password=root;database=student"
}
参考网址:
[1]: https://blog.csdn.net/weixin_44146294/article/details/110949332
[2]: https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql