.net core 3.1 mysql_.net core 3.1 连接mysql
时间: 2023-08-01 18:10:44 浏览: 140
首先,需要在项目中添加 MySQL.Data NuGet 包。
然后,在 appsettings.json 文件中添加 MySQL 数据库的连接字符串,例如:
```
"ConnectionStrings": {
"DefaultConnection": "server=localhost;database=mydatabase;user=root;password=123456;"
}
```
接下来,在 Startup.cs 文件中的 ConfigureServices 方法中添加 MySQL 数据库的服务,例如:
```csharp
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MySql.Data.EntityFrameworkCore.Extensions;
public void ConfigureServices(IServiceCollection services)
{
// 获取连接字符串
var connectionString = Configuration.GetConnectionString("DefaultConnection");
// 添加 MySQL 数据库的服务
services.AddDbContext<MyDbContext>(options =>
options.UseMySQL(connectionString)
);
}
```
最后,在 MyDbContext.cs 文件中,定义 MySQL 数据库的上下文类,例如:
```csharp
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<MyEntity> MyEntities { get; set; }
}
```
这样就完成了 .NET Core 3.1 和 MySQL 数据库的连接。可以通过 MyDbContext 类来访问 MySQL 数据库中的数据。
阅读全文
相关推荐















