DbContextOptionsBuilder 在 ASP.NET Core 6 项目中没有按预期工作?

DbContextOptionsBuilder is not working as expected at ASP.NET Core 6 project?

当我如下配置我的启动文件时,

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();