尝试使用以下代码示例来解决该问题:
首先,确保你的项目中已经安装了Microsoft.EntityFrameworkCore包。
在Startup.cs文件中,先注入DbContextOptions,然后使用AddDbContext方法添加DbContext。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
MyDbContext是你的DbContext类。通过上述代码,你的DbContext配置就已经完成了。
在Controller中,你可以通过构造函数依赖注入(DI)获取DbContext,如下所示:
public class MyController : Controller
{
private readonly MyDbContext _context;
public MyController(MyDbContext context)
{
_context = context;
}
}
现在你可以使用MyDbContext来操作数据库了。