0

面对上述问题时,甚至遵循了Connection Strings - EF Core的简单演练,但发现在将连接字符串硬编码为:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}

导致成功,使用插入 App.config 文件的推荐方法,例如:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="BloggingDatabase"
         connectionString="Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

并将主代码更新为:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
}

不成功,并且在执行迁移时遇到以下错误:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Intro.BloggingContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\<...FileLocation...>\AppDbContext.cs:line 14
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at 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.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

背后的原因可能是什么?

提前感谢您的审阅和回复。

4

2 回答 2

0

奇怪的!!!使用索引技术时,例如:optionsBuilder.UseSqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString); 成功了!– Faraz Ahmed Qureshi 3 月 28 日 17:06

确实这有效

于 2020-12-15T00:58:31.763 回答
0

终于在这里找到了一个镜像问题的唯一令人满意的答案。

App.Config 不是WPF Core连接字符串的正确选择。在这方面,它是一个足够成功的 appsettings.json 文件。

于 2020-04-17T17:47:33.063 回答