ConfigurationManager在添加迁移时用于提取数据库连接字符串时返回null

eyv*_*vaz 9 c# configuration .net-core entity-framework-core-2.2

我在我的 .NET Core 控制台应用程序中使用 Entity Framework Core。我将连接字符串存储在App.config文件中,并ConfigurationManager在上下文类中使用以访问连接字符串。

当我想向我的项目添加新迁移时,出现以下错误:

System.NullReferenceException:未将对象引用设置为对象的实例。

在 EF_tut.Context.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\..\Context.cs:line 12
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure1 accessor)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func
1 个工厂)在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor。 AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

你调用的对象是空的。

这是我的App.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
         <add name="EfTutDb" 
              connectionString="Data Source=.;Initial Catalog=EF_tut;Integrated Security=True;"/>
    </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

这是我的上下文类:

class Context : DbContext
{
    public DbSet<Student> Students { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["EfTutDb"].ConnectionString); // Line 12.
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试ConfigurationManger在 main 方法中使用获取连接字符串时,我得到了连接字符串,但是当我添加迁移时,我得到了空引用错误。

小智 -1

我不太确定,但我认为你必须修复连接字符串。在你的课堂上试试这个:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=YourPcName\\YourSqlServerName;Database=YourDbName;Trusted_Connection=True;MultipleActiveResultSets=True;");
        }
    }
Run Code Online (Sandbox Code Playgroud)