c# - 为什么不能使用 = 运算符设置 DbContextOptions?

标签 c# entity-framework-core

为什么我不能使用下面的

IServiceCollection service= new ServiceCollection();
var opt = new DbContextOptionsBuilder<Application>().UseSqlite("Data Source=MyDatabase.db");
service.AddDbContextPool<ApplicationContext>(options => options = opt);

而不是下面的 ?

IServiceCollection service= new ServiceCollection();
service.AddDbContextPool<ApplicationContext>(options => options.UseSqlite("Data Source=MyDatabase.db"));

编辑:

错误信息:

System.InvalidOperationException
  HResult=0x80131509
  Message=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<TContext> object in its constructor and passes it to the base constructor for DbContext.
  Source=Microsoft.EntityFrameworkCore
  StackTrace:
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure`1 databaseFacade)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
....

最佳答案

在这里,(options => options = opt) 就像常规方法一样工作:

private void Method(TypeOfParameter options)
{
    options = opt;
}

这里,options 变量只是被覆盖了。在方法之外没有任何事情发生。用于调用该方法的变量未更改。这就是赋值无用且没有任何效果的原因。

关于c# - 为什么不能使用 = 运算符设置 DbContextOptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48618813/

相关文章:

c# - EF核心3 : CLR property 'Number' cannot be added to entity type 'CHSIMTBase' because it is declared on the CLR type 'Contract'

c# - 从 C# 中的文本文件中读取矩阵

c# - 确定 WPF 元素类型

c# - LINQ 中的 SQL LIKE

asp.net-core - 什么可能导致 `UserManager` 返回错误的用户?

entity-framework - .net core 2.1同一数据库的多个DbContext

c# - 将同一列中的不同值相互附加

c# - ClickOnce部署的应用程序注册表权限问题

c# - Entity Framework Core 急切加载然后包含在集合中

c# - Entity Framework Core 的 MySQL 排序规则问题