When I configure my Startup file as below,
public void ConfigureServices(IServiceCollection services)
{
var dbContextOptions = new DbContextOptionsBuilder<StoreContext>();
dbContextOptions.UseSqlite(_config.GetConnectionString("DefaultConnection"));
if (_env.IsDevelopment())
{
dbContextOptions.EnableSensitiveDataLogging();
}
services.AddDbContext<StoreContext>(x => x = dbContextOptions);
services.AddApplicationServices(_env, _config);
services.AddAutoMapper(typeof(MappingProfiles));
services.AddControllers();
services.AddSwaggerDocumentation();
services.AddCors();
}
the app gives me the below error:
System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
When I changed this line
services.AddDbContext<StoreContext>(x => x = dbContextOptions);
to
services.AddDbContext<StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
then it is working. But what am I missing, why doesn't work first code.
CodePudding user response:
I believe the issue is you are assigning parameter passed into an action you are creating by x => x = dbContextOptions
, which is in the beginning reference to existing instance of options, but it would’t change reference outside of the action. Just inside the action the reference is changed.
Try this.
string original = "original";
Action<string> action = x => x = "new";
action(original);
Console.WriteLine(original); // Output: original
Console.ReadKey();