Accessing the connection string in Entity Framework Core 6

1.2k views Asked by At

I'm doing my first app in .NET 6 and using Entity Framework Core 6, using database first and the Scaffold-DbContext command to create the DbContext.

The only issue I have is trying to use the Name={connection string name} parameter rather than embedding the connection string. The app is a simple Console app (not an ASP.NET app) with an app.config file (can't use a JSON config file for other reasons). I added the connection to the config file like:

<connectionStrings>
    <add name="MyDatabase" 
         connectionString="Server=xxxxxxx;Database=xxxxxxx;Trusted_Connection=True"/>
</connectionStrings>

I get this error:

A named connection string was used, but the name 'ClientServices' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

What do I need to do so that the Scaffold-DbContext Name parameter can find my connection string? Looked at the link in the error, but it didn't help - was for ASP.NET apps.

1

There are 1 answers

0
Axel Samyn On

In case anyone is struggeling with this, here's the documentation that should help you out.

For a WPF app, you should at least ad this code for the scaffold command to work:

  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using System.Windows;


  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    public App()
    {
      using IHost host = Host.CreateDefaultBuilder().Build();

      var config = host.Services.GetRequiredService<IConfiguration>();

      host.Run();
    }
  }

Put the code in Program.cs/Main in case this matches your project's template.