如何根据配置切换EF Core使用的数据库提供程序? [英] How can I switch the database provider used by EF Core based on configuration?
问题描述
EF Core支持许多不同的提供程序,我可以通过指定提供程序在 Startup.cs
中对其进行配置.例如,如果要使用SQL Server,可以使用:
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"));
});
但是,数据库提供程序(SQL Server)似乎在此处进行了硬编码.我要实现的是基于配置设置数据库提供程序,因此我可以基于配置切换数据库提供程序.
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?
推荐答案
可以,但这有点手册.您可以从此处访问配置,因此您可以执行以下操作:
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.
这篇关于如何根据配置切换EF Core使用的数据库提供程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!