genxgeek
genxgeek

Reputation: 13357

How to connect to another DB with an already existing EF (4.1) DbContext?

I'm pretty new to EF and use to old school SqlConnection....

Question: I have an existing mvc3/EF database context object that already hits a local sql server 2008 instance. I want to add a new connection string in the web config and have the existing DBContext connect to a remote database to run a stored proc.

How can I do this?

Upvotes: 0

Views: 707

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

If by existing context you mean the same context instance than it is not possible: one context instance = one connection string.

If you need to connect to two databases you need two context instances and pass connection string to them. Even in such case it can have many restrictions depending on your EF usage. Using the same context type for databases with different schema (different tables) doesn't always work as expected.

When using completely different databases the best way is to have two different context types and instance of each of them. But if you only want to execute stored procedure the simplest way is simply use ADO.NET SqlCommand and SqlConnection directly.

Upvotes: 2

Manu Clementz
Manu Clementz

Reputation: 1797

One of the ObjectContext constructors takes a connection string as a parameter. That should help.

Upvotes: 1

Related Questions