Erdinç
Erdinç

Reputation: 267

Using 2 Databases With Linq

I am just writing an asp.net application and i wonder how to connect and query 2 different databases with linq. 2 databases have same tables and same rows and same identicals. Only database names and data is different on them. I know linq classes mapping and creating just one db with it tables and rows. If i change connectionstring other databases which are same. Could this be possible? If anyone try this and get any issues? And how can i change connectionstring on runtime? I mean i can use combobox or something like this, but do i have to add appsettings to add connectionstring to look for or do i need to change linq mapping classes to reach dbs? i am very confused. i need your helps.

Upvotes: 0

Views: 72

Answers (2)

Anders Abel
Anders Abel

Reputation: 69310

Set up LINQ-to-SQL or Entity Framework (to use LINQ-to-Entities) to one of the databases. At run time you can use the DataContext/DbContext constructor overload that takes a specific connection string to decide what database to use.

Upvotes: 2

Fred Francisco
Fred Francisco

Reputation: 146

When using Entity Framework, when you instantiate a DataContext you get a constructor that accepts a sqlConnection object that contains a connection string. Something like (i don't know the exact syntax and class names by heart):

SqlConnection sqlcon = SqlConnection(YourConnectionString); DataContext db = DataContext(sqlcon);

In LINQ, i do think that there's also one for it. You can store a key-value pair in Web.Config with different connection string and figure out in your code how to switch from one connection to another.

Upvotes: 2

Related Questions