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

妖精的绣舞 提交于 2021-02-20 00:25:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!