Когда я настраиваю свой файл запуска, как показано ниже,
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();
}
приложение выдает мне следующую ошибку:
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.
Когда я изменил эту строку
services.AddDbContext<StoreContext>(x => x = dbContextOptions);
к
services.AddDbContext<StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
тогда он работает. Но что я упускаю, почему не работает первый код.
Я полагаю, проблема в том, что вы назначаете параметр, передаваемый в действие, которое вы создаете с помощью x => x = dbContextOptions
, которое в начале является ссылкой на существующий экземпляр параметров, но не изменит ссылку вне действия. Просто внутри действия ссылка меняется.
Попробуй это.
string original = "original";
Action<string> action = x => x = "new";
action(original);
Console.WriteLine(original); // Output: original
Console.ReadKey();
Добро пожаловать!
ты прав, спасибо