Saravana
Saravana

Reputation: 40594

How can I switch the database provider used by EF Core based on configuration?

EF Core supports a lot of different providers and I can configure them in Startup.cs by specifying the provider. For example, if I want to use SQL Server, I can use:

services.AddDbContext<SomeContext>(options => {
    options.UseSqlServer(Configuration.GetConnectionString("SomeDatabase"));
});

But the DB provider (SQL Server) seems to be hard-coded here. What I want to achieve is set the DB provider based on configuration so I can switch the DB provider based on configuration.

Is there a way to switch provider based on config?

Upvotes: 2

Views: 3536

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

You can, but it's a bit manual. You have access to the config from here, so you can just do something like:

services.AddDbContext<SomeContext>(options => Configuration["DatabaseProvider"] switch
{
  "someprovider" => options.UseSomeOtherProvider(...),
  // etc.
  _ => options.UseSqlServer(Configuration.GetConnectionString("SomeDatabase"))
});

I'm using the newer switch expression syntax here. The last line with _ implies the default when there's no explicit match.

Upvotes: 5

TomTom
TomTom

Reputation: 62093

Not really. YOu must make your own factory method. See, this is not just configuring - this is also loading the classes. There is no registration mechanism for this anymore in web.config.

Upvotes: 1

Related Questions