如何在实体框架解决方案中同时使用多个数据库?

时间:2021-05-24 09:45:30

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!

我有两个不相关的数据库,我需要在它们之间来回传递数据。现在我已经创建了两个独立的实体模型——一个为每个数据库——但这是导致我的代码问题b / c我必须做一个使用nameofcontext /结束使用,然后当我试着使用一些代码的第一部分的结果在第二个使用nameofcontext /结束使用它不喜欢它- b / c我关闭了连接到第一个数据库!

1 个解决方案

#1


3  

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.

由于这是一个网站,您可以在全局中创建每个上下文的一个实例。asax的BeginRequest事件,并在EndRequest中处理该实例。这样做意味着在事件生命周期的其余部分,您将拥有保持开放的上下文,并且可以执行所需的操作,但是您仍然知道它们正在被正确地处理。

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.

注意:不要将上下文存储在全局共享变量中,因为这会在多个请求之间共享上下文,而havok将确保这一点。HttpContext.Current。项允许您在代码中存储一些易于检索但特定于当前请求的内容,因此这是存储它们的安全场所。

#1


3  

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.

由于这是一个网站,您可以在全局中创建每个上下文的一个实例。asax的BeginRequest事件,并在EndRequest中处理该实例。这样做意味着在事件生命周期的其余部分,您将拥有保持开放的上下文,并且可以执行所需的操作,但是您仍然知道它们正在被正确地处理。

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.

注意:不要将上下文存储在全局共享变量中,因为这会在多个请求之间共享上下文,而havok将确保这一点。HttpContext.Current。项允许您在代码中存储一些易于检索但特定于当前请求的内容,因此这是存储它们的安全场所。