Gil*_*rdo 13 c# entity-framework entity-framework-core asp.net-core-mvc asp.net-core
使用Entity Framework 7和MVC6时,我似乎收到此错误消息
System.InvalidOperationException未配置任何数据库提供程序.在设置服务时,通过在DbContext类或AddDbContext方法中覆盖OnConfiguring来配置数据库提供程序.
我相信我已经做了我应该做的一切,所以也许它是一个错误.我使用的是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方法,因为我认为不需要它,因为我正在完成上述所有操作?我对吗?我错过了什么?看了很多不同的网站,我猜有些人正在使用旧代码,因为有些方法不存在,而其他网站与我拥有的相同.
Nic*_*eer 26
设置下面显示的MyDbContext以注入Startup.cs AddDbContext()调用中定义的options参数.
public MyDbContext(DbContextOptions options)
: base(options)
{ }
这将允许您将连接字符串从Configuration(config.json)传递给方法调用options.UseSqlServer()
services.AddEntityFramework()
    .AddSqlServer()
    .AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"]));
当我不得不将我的解决方案拆分为单独的项目Web,BL和DAL时,我遇到了同样的问题.
| 归档时间: | 
 | 
| 查看次数: | 6703 次 | 
| 最近记录: |