1

I created a .net core 2.1 console app in vs2019. In the DB context OnConfiguring method, I have:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConsoleApp1Core"].ConnectionString; // this does not work
    var conn = "User Id=xxx;Password=xxx;Data Source=xxx:xxx/xxx"; // this works
    optionsBuilder.UseOracle(conn);
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ConsoleApp1Core" connectionString="User Id=xxx;Password=xxx;Data Source=xxx:xxx/xxx" />
  </connectionStrings>
</configuration>

error:

PM> get-dbcontext
System.NullReferenceException: Object reference not set to an instance of an object.
   at ConsoleApp1Core.Program.BloggingContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\ConsoleApp1Core\Program.cs:line 21
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.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.DbContextOperations.GetContextInfo(String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.GetContextInfoImpl(String contextType)
   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.
Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
  • 1
    See [this answer](https://stackoverflow.com/a/50528482/2091410) to [this question](https://stackoverflow.com/q/46996480/2091410). Though not the accepted answer, I think it may help. It states that you need to install the `System.Configuration.ConfigurationManager` NuGet package. – Ed Gibbs Aug 10 '19 at 01:57
  • @EdGibbs Thank you. I got the answer from a different post in that question. – Ray Cheng Aug 12 '19 at 15:39

1 Answers1

1

The problem was I forgot to set App.config to copy to output directory. Got the hint from https://stackoverflow.com/a/46999609/310767.

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137