Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I utilize multiple databases in an entity framework solution simultaneously?

I have two unrelated databases and I need to pass data back and forth between them. Right now I have created two separate entity models - one for each database - but this is causing issues in my code b/c I have to do a Using nameofcontext / End Using and when I try to then use some of the results from the first section of the code in a second Using nameofcontext / End Using it doesn't like it - b/c I've closed the connection to the first database!

like image 677
Dave Mackey Avatar asked Feb 14 '26 10:02

Dave Mackey


1 Answers

Since this is a website, you could create one instance of each context in Global.asax's BeginRequest event, and dispose of that instance in EndRequest. Doing that means during the rest of the event lifecycle, you have contexts that will remain open and can do what you need, but you still know they're being properly disposed.

That's how I've gotten around issues like this.

Note: Don't store the context in a global shared variable because that will share it between multiple requests and havok will ensure. HttpContext.Current.Items lets you store something that is easy to retrieve in your code but is specific to the current request, so that's a safe place to store them.

like image 123
Tridus Avatar answered Feb 15 '26 23:02

Tridus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!