ef core webapi 配置上下文
时间: 2023-12-13 10:05:02 浏览: 30
在使用 Entity Framework Core (EF Core) 进行 Web API 开发时,需要进行上下文的配置。以下是一个基本的 EF Core 上下文配置示例:
1. 首先,需要在项目中安装 Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.SqlServer NuGet 包。
2. 在项目中添加一个 DbContext 类,该类继承自 Microsoft.EntityFrameworkCore.DbContext。
```csharp
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<MyEntity> MyEntities { get; set; }
}
```
3. 在 Startup.cs 文件中的 ConfigureServices 方法中添加以下代码:
```csharp
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));
```
其中,MyDbContext 是你创建的 DbContext 类的名称,MyConnectionString 是连接字符串的名称。
4. 在 appsettings.json 文件中添加连接字符串:
```json
"ConnectionStrings": {
"MyConnectionString": "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
}
```
其中,"Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;" 是你的数据库连接字符串。
完成上述步骤后,你就可以在 Web API 中使用 MyDbContext 类来访问数据库了。