Payam Sh
Payam Sh

Reputation: 601

How to work with two databases having the same tables in C#?

I'm writing a program & I want to have 2 SQL Server databases. One on the client and one on the server. I would like to check the internet connectivity in my program and if the user is connected to the internet the server database is used and if it's offline then the client database is used and then when the user connects to the internet the server database updates itself with the client database.

As the two databases are exactly the same and have the same tables how can I do this? I mean connection strings and the dbml file contents.

Upvotes: 2

Views: 698

Answers (2)

StuartLC
StuartLC

Reputation: 107237

Since you've mentioned dbml, I've assumed LINQ2SQL.

I would suggest you add 2 connection strings, one for client, one for server.

Then use the DataContext() constructor which takes the connection string name to determine which database the context points to. e.g. here

Edit

I would suggest a helper method / factory something like this:

public static MyDataClassesContext GetDataContext(bool isInternetAvailable)
{
  if (isInternetAvailable)
  {
    return new MyDataClassesContext("ServerConnStringName");
  }
  else
  {
    return new MyDataClassesContext("LocalConnStringName");
  }
}

And in your code using DataContexts:

    // Whatever your mechanism is for determining internet availability 
    // (Note that you probably want to cache this bool lol)
    bool isInternetAvailable = GetPingToServer() < 10000 ? true : false;
    using (var dc = GetDataContext(isInternetAvailable))
    {
        ...
    }

Upvotes: 3

Oliver
Oliver

Reputation: 45071

You should take a look into the Microsoft Sync Framework. It says from itself:

A comprehensive synchronization platform that enables collaboration and offline access for applications, services, and devices with support for any data type, any data store, any transfer protocol, and any network topology.

And it has everything prepared to cover exact your scenario.

Upvotes: 0

Related Questions