ROBERT RICHARDSON
ROBERT RICHARDSON

Reputation: 2289

Is it possible to use Entity Framework Core with ODBC?

My company's main software application hasn't been updated in twenty years. I expect to soon be working on a complete rewrite of it. To that end, I am beginning to work my way through the book "Pro ASP.Net Core 3" by Adam Freeman (8th edition).

Our application was written to be independent of specific database types. Most of our customers use PostgreSQL, but a few use SQL Server. Therefore, we use ODBC because ODBC drivers exist for both of those databases, as well as several others. The application does not do anything fancy with the databases, and ODBC works well. We configure an ODBC DSN to talk to whichever database the customer has, and the application itself doesn't have to be changed.

A search on "Entity Framework Core ODBC" led me to the EF Core Github, where people have asked similar questions, and the answers were mostly along the lines of "why on earth would you want to do that?". Well, I need to do that.

Can I use EF Core with ODBC, or is there some other way that I can set up an Entity Framework Core application that does not have to be modified if the underlying database changes from PostgreSQL to SQL Server?

Upvotes: 2

Views: 3654

Answers (1)

Chad Hollenbeck
Chad Hollenbeck

Reputation: 36

You could use your appsettings.json to store a value used to swap between the two. Those environment configs get reloaded on change (though you might have to restart your application to read them again, I'm not sure on that one).

Regardless something along the lines of this would suit your needs I think.

if (Configuration.GetSection("dbOptions")["postgres"]))
    services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("PostgresConnectionString")));
  else
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnectionString")));

EDIT: I placed this in Startup.cs where you would normally configure the DBContext. I use a similar solution reading off the Environment type to load either the Prod or QA connection strings based on deployment. In principle, this should accomplish the same task without the need for rebuilding and redeploying the code base.

Upvotes: 1

Related Questions