在使用Entity Framework 7和MVC6时,我似乎遇到了这个错误消息。
System.InvalidOperationException:未配置任何数据库提供程序。通过在您的DbContext类中重写OnConfiguring方法或在设置服务时的AddDbContext方法中重写该方法来配置数据库提供程序。
我相信我已经做了应该做的一切,所以可能是个bug。我正在使用Entity Framework的7.0.0-beta7版本。
我已经设置好了我的DbContext,还有一个接口,这样我就可以模拟DbContext(在EntityFramework 6中进行单元测试时需要)。我的服务使用接口作为构造函数,并在MVC 6中设置了DI。
在我的Startup.cs文件中,我有以下内容
public void ConfigureServices(IServiceCollection services)
{
// entity framework
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"])
);
// Add MVC services to the services container.
services.AddMvc();
// new context on each request
services.AddScoped<IMyDbContext, MyDbContext>();
}
我已经检查了我的connectionString并且返回了有效的连接。我还在我的服务中检查了被注入的对象,它不是null,所以应该都可以工作。
我的config.json文件看起来像这样
{
"Data": {
"MyConnection": {
"ConnectionString": "Server=(local);Database=XXXX;Trusted_Connection=True;"
}
}
}
我的DbContext没有覆盖OnConfiguring方法,因为我认为不需要,因为我已经按照上述方式完成了所有操作。 我是对的吗? 我错过了什么?查看了许多不同的网站,我猜有些网站使用的是旧代码,因为一些方法不存在,而其他网站与我拥有相同的方法。
MyDbContext
? - DavidG