1

I have an ASP.NET Core Web API project referencing an EF Core project.

When I scaffolded the EF Core project, it automatically set up the connection string within the OnConfiguring method:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=etc;Database=etc;uid;pwd;");
    }
}
    

Then I found out that the equivalent of placing the connection string in a web.config is to place it within an appSettings.json file of the Web API project, and read it in the ConfigureServices method of the Startup class of the Web API project etc...

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c => ...);

    var CNN_STR = Configuration.GetConnectionString("DBNameInAppSettingsJson");
    services.AddDbContext<MyDBContext>(options =>
        options.UseSqlServer(CNN_STR));
}

But now the connection string is in two places! Am I supposed to remove it from the OnConfiguring() method of the EF Core project? If so, how?

5
  • The second connection string wil be only used when (!optionsBuilder.IsConfigured). But it is configured in startup already Commented Jul 10, 2021 at 21:18
  • Have the same issue. One is needed for creating the migrations and the other is used for the normal running application. The only thing I came up with is to create an instance of IConfigurationRoot using Microsoft.Extensions.Configuration.ConfigurationBuilder in the OnConfiguring() or the IDesignTimeDbContextFactory for it. This won't remove the code for setting the connection string, but at least both places get the same connection string from the config. Commented Jul 10, 2021 at 21:19
  • @Serge, yes it is configured in Startup already BUT when the code runs the check .IsConfigured, it still shows false, which surprised me ! (this is for .NET 5.0) Commented Jul 10, 2021 at 21:23
  • @joedotnot I just checked my net5 application, isconfigured is true. So maybe you need to recheck if you properly configured it. And for migration it is using startup configuration too. Or just try to comment dbcontext code and see it it works properly. Commented Jul 10, 2021 at 21:59
  • 1
    There is an option to not include the onconfiguring code. Commented Jul 11, 2021 at 5:44

1 Answer 1

2

The preferable approach is to use Dependency Injection (have a search on that term) by using ConfigureServices in Startup.cs.

Then, have the configured DbContext injected where you need it (you'll see more on that in the documentation), instead of manually instantiating the DbContext when you want it.

https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

Re your comment that IsConfigured is still false, this is probably because you are manually instantiating the DbContext somewhere, rather than injecting it (dependency injection). If you inject it, you'll get the configured version from ConfigureServices. If you instantiate it manually you'll get an unconfigured version.

If you want a configured version of your DbContext in a Controller, then use the following:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c => ...);

    var CNN_STR = Configuration.GetConnectionString("DBNameInAppSettingsJson");
    services.AddDbContext<MyDBContext>(options =>
        options.UseSqlServer(CNN_STR));
}

Controller

public class MyController : ControllerBase
{
    private readonly MyDbContext _Context;
    
    public MyController(
        MyDbContext context)
    {
        // The parameter 'context' is provided by ASP Dependency Injection
        // ... It will be the configured version from above startup.cs
        _Context = context;
    }

    public async Task DoSomething()
    {
        // Use the configured context
        await _Context.Widgets.AddAsync(new Widget());
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

"this is probably because you are manually instantiating the DbContext somewhere", this is exactly what I'm doing, as in Full Fx 4.x it automagically injects from web.config. Will come back to accept your answer after I try it out.
I was missing the Controller constructor because VS2019 does not automatically create one when I use its Add Controller wizard, hence I wasn't aware of the possibilities. Thanks to this answer, I can now remove the OnConfiguring(...) method in the EF project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.