Sar*_*ana 2 c# entity-framework entity-framework-core asp.net-core
EF Core 支持许多不同的提供程序Startup.cs,我可以通过指定提供程序来配置它们。例如,如果我想使用 SQL Server,我可以使用:
services.AddDbContext<SomeContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("SomeDatabase"));
});
Run Code Online (Sandbox Code Playgroud)
但数据库提供程序(SQL Server)似乎在这里是硬编码的。我想要实现的是根据配置设置数据库提供程序,以便我可以根据配置切换数据库提供程序。
有没有办法根据配置切换提供商?
可以,但是有点手动。您可以从这里访问配置,因此您可以执行以下操作:
services.AddDbContext<SomeContext>(options => Configuration["DatabaseProvider"] switch
{
"someprovider" => options.UseSomeOtherProvider(...),
// etc.
_ => options.UseSqlServer(Configuration.GetConnectionString("SomeDatabase"))
});
Run Code Online (Sandbox Code Playgroud)
我在这里使用较新的 switch 表达式语法。最后一行_表示没有显式匹配时的默认值。