No database providers are configured EF7

旧城冷巷雨未停 提交于 2019-11-30 17:38:33

Setup your MyDbContext shown below to inject the options parameter defined in Startup.cs AddDbContext() call.

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

This will allow you to pass your connection string from the Configuration (config.json) into the method call options.UseSqlServer()

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

I encountered the same problem when I had to split my solution into separate projects Web, BL, and DAL.

I belive that you hit this error on the line where you trying to access some data from database. You can resolve this problem by confiuguring your context. Just override OnConfiguring method.

public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer("<your connection string>");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        ...
    }
}

I hit this problem in Visual Studio 2015 a couple of weeks ago.

I had to add the Context to the dependency injection collection in startup.cs.

See here for more detail - http://nodogmablog.bryanhogan.net/2016/01/how-to-fix-no-database-providers-are-configured-when-scaffolding-a-controller-in-asp-net-5/

Mithun Poddar

Try the following:

public class DataContext<TEntity> : DbContext where TEntity : class
{

    private TEntity _entity = null;
    public DataContext()
        : base()
    {

    }
    public DataContext(TEntity entity)
    {
        this._entity = entity;
    }
    public DbSet<TEntity> 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"]);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!