0

I am using C# and I need to have dynamic contexts meaning. lets say i have scaffolded on db1 and users dB, after user logins I take connection string of db2 from users dB and now i want to use db2 instead of db1. the models of db1 and db2 are exactly the same. there are more than 20 db with same models which need to change dynamically. How do i achieve this so i can use LINQ on db2 context and also there are lot of different query's running though I cant create and dispose of context for db2 every time. Also to keep in mind this DB is in postgres sql

I wanted to try just by saving created contexts in he same class but i think not disposing of them and can cause problems

  • isn't `DbContext` initialization can take parameters on which connection it should hit? – Bagus Tesa Jul 11 '23 at 07:31
  • @BagusTesa can u provide example i am quite new to this – Alexandr Skhirtladze Jul 11 '23 at 11:08
  • check [this QA](https://stackoverflow.com/a/38418080), specifically on the part *"If you **really** want to create the context manually, then you can configure it like this."* you can at least choose which connection string you want to feed the `DbContext`. – Bagus Tesa Jul 11 '23 at 11:12
  • you can have multiple contexts with seperate connection strings. could you elaborate what you mean by "changing models dynamically"? the question is hard to understand for me. – Emre Bener Jul 11 '23 at 14:27
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 11 '23 at 14:27
  • There are many ways to do this. Extract a common interface, and then use a factory to provide your DB context as a scoped dependency. The factory can examine the authentication state. – Aluan Haddad Jul 13 '23 at 15:26
  • you can have multiple database context files. you don't have to dynamically switch between them. just initialize all of your contexts, and use whichever one you want within code. – Emre Bener Jul 27 '23 at 10:53

0 Answers0