Working on my first MVC Core project and I'm trying to get the database context setup in the config services of Startup.cs but keep getting the error:
No database provider has been configured for this DbContext.
If I use the OnConfiguring override in the DbContext it works. This code will connect:
public partial class DataContext : DbContext
{
public DataContext()
{
}
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public virtual DbSet<AbraEmployee> AbraEmployee { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json", optional: false)
.Build();
optionsBuilder.UseOracle(configuration.GetConnectionString("DbConnection"));
}
}
}
However, if I comment that out and use the following in my Start.cs then I get the error.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<IDataManager, DataManager>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//setting connstring separately here just to be able confirm correct value.
var connstring = Configuration.GetConnectionString("DbConnection");
services.AddDbContext<DataContext>(options => {
options.UseOracle(connstring);
});
}
I've looked at several different posts about the error but all basically say to make sure to have the constructor in DbContext accept DbContextOptions which my context seems to be setup correctly. The only other thing I found was to make sure to have IHttpContextAccessor in the ConfigServices.
Anyone have an idea on what I'm missing?
question from:
https://stackoverflow.com/questions/65833073/entity-framework-core-3-no-database-provider-error 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…