没有数据库提供程序配置EF7

使用Entity Framework 7和MVC6时,我似乎收到此错误消息

System.InvalidOperationException未配置任何数据库提供程序。 在设置服务时,通过在DbContext类或AddDbContext方法中覆盖OnConfiguring来配置数据库提供程序。

我相信我已经做了我应该做的一切,所以也许它是一个错误。 我使用的是Entity Framework的7.0.0-beta7版本。

我已经设置了我的DbContext,一个接口,所以我可以模拟DbContext(在EntityFramework 6中需要进行unit testing)。 我的服务将接口作为构造函数,我在MVC 6中设置了DI。

在我的Startup.cs文件中,我有以下内容

public void ConfigureServices(IServiceCollection services) { // entity framework services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"]) ); // Add MVC services to the services container. services.AddMvc(); // new context on each request services.AddScoped(); } 

我已经检查了我的connectionString,并且返回了一个有效的连接。 我还检查了我的服务,正在注入该对象,并且它不是null,因此应该全部工作。

我的config.json文件看起来像这样

 { "Data": { "MyConnection": { "ConnectionString": "Server=(local);Database=XXXX;Trusted_Connection=True;" } } } 

我的DbContext没有覆盖OnConfiguring方法,因为我认为不需要它,因为我正如上所述那样做? 我对吗? 我错过了什么? 看了很多不同的网站,我猜有些人正在使用旧代码,因为有些方法不存在,而其他网站与我拥有的相同。

设置下面显示的MyDbContext以注入Startup.cs AddDbContext()调用中定义的options参数。

 public MyDbContext(DbContextOptions options) : base(options) { } 

这将允许您将连接字符串从Configuration(config.json)传递到方法调用options.UseSqlServer()

 services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:MyConnection:ConnectionString"])); 

当我不得不将我的解决方案拆分为单独的项目Web,BL和DAL时,我遇到了同样的问题。

我相信您在尝试从数据库访问某些数据的行上遇到此错误。 您可以通过配置上下文来解决此问题。 只需覆盖OnConfiguring方法即可。

 public class MyDbContext : DbContext { public DbSet Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlServer(""); } protected override void OnModelCreating(ModelBuilder modelBuilder) { ... } } 

几个星期前我在Visual Studio 2015中遇到了这个问题。

我必须将Context添加到startup.cs中的dependency injection集合中。

有关更多详细信息,请参见此处 – http://nodogmablog.bryanhogan.net/2016/01/how-to-fix-no-database-providers-are-configured-when-scaffolding-a-controller-in-asp-net- 5 /

请尝试以下方法:

 public class DataContext : DbContext where TEntity : class { private TEntity _entity = null; public DataContext() : base() { } public DataContext(TEntity entity) { this._entity = entity; } public DbSet Entity { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultSchema("dbo"); } public IConfigurationRoot Configuration { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); Configuration = configuration.Build(); optionsBuilder.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]); } }