问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/60976990/how-can-i-switch-the-database-provider-used-by-ef-core-based-on-configuration