0

I have an application that uses Entity Framework 6 to connect to an SQL Server database. We need to change this to also use a PostgreSQL database at the same time. What I'm after is three DbContext. One that always connects to SQL Server, one that always connects to PostgreSQL and one that changes which database it uses depending on a config setting. I'm confused as to how I would set up these connections. The code we have passes a connection string directly into the DBContext constructor.

The connection string being passed has no information about the database type. It is something like this:

"Server=example;Database=MyDb;Trusted_Connection=True;"
Martin Brown
  • 24,692
  • 14
  • 77
  • 122
  • 1
    Wouldn't you just pass a connection string to your DbContext constructor? EF is neutral for all the providers that support EF. There is an EntityConnection. – Cetin Basoz Jul 31 '18 at 09:57
  • But how does it know what sort of database it is connecting to? Surely it needs to know which database provider to use. – Martin Brown Jul 31 '18 at 09:58
  • It doesn't need to. Connection string gives the information about the backend and the dialect it translates is not backend specific. – Cetin Basoz Jul 31 '18 at 09:59
  • Just looks like a standard SQL Connection string to me. I've put an example in the question. Do I need to add something to it? – Martin Brown Jul 31 '18 at 10:00
  • If you give the context the name of the connection string, it should pick up the provider from there. Your connection strings should look something like this `` – DavidG Jul 31 '18 at 10:03
  • Yes but the "SQL" that is translated is not a backend specific SQL. It is provider's job to do the rest. – Cetin Basoz Jul 31 '18 at 10:06
  • @CetinBasoz that brings me back to the point of how does it know which provider to use. – Martin Brown Jul 31 '18 at 10:25
  • 1
    @DavidG is there no way to specify the provider at runtime? We have quite a complex environment and the current connection string comes out of a secrets manager rather than the config file. This is because the security team don't want database passwords sitting around in plain text on disk. – Martin Brown Jul 31 '18 at 10:26
  • 1
    Something like this? https://stackoverflow.com/questions/29440405/entity-framework-6-set-connection-string-runtime – DavidG Jul 31 '18 at 10:51

0 Answers0