How do I synchronize the two types of data and update them in the database?

I am trying to sync two tables between two databases. I thought the best way to do this is using the DataTable.Merge method. This seems to pick up changes, but nothing is ever tied to the database.

So far I have:

string tableName = "[Table_1]";
        string sql = "select * from " + tableName;

        using (SqlConnection sourceConn = new SqlConnection(ConfigurationManager.ConnectionStrings["source"].ConnectionString))
        {
            SqlDataAdapter sourceAdapter = new SqlDataAdapter();

            sourceAdapter.SelectCommand = new SqlCommand(sql, sourceConn);
            sourceConn.Open();
            DataSet sourceDs = new DataSet();
            sourceAdapter.Fill(sourceDs);

            using (SqlConnection targetConn = new SqlConnection(ConfigurationManager.ConnectionStrings["target"].ConnectionString))
            {
                SqlDataAdapter targetAdapter = new SqlDataAdapter();

                targetAdapter.SelectCommand = new SqlCommand(sql, targetConn);

                SqlCommandBuilder builder = new SqlCommandBuilder(targetAdapter);

                targetAdapter.InsertCommand = builder.GetInsertCommand();
                targetAdapter.UpdateCommand = builder.GetUpdateCommand();
                targetAdapter.DeleteCommand = builder.GetDeleteCommand();

                targetConn.Open();
                DataSet targetDs = new DataSet();
                targetAdapter.Fill(targetDs);

                targetDs.Tables[0].TableName = tableName;
                sourceDs.Tables[0].TableName = tableName;
                targetDs.Tables[0].Merge(sourceDs.Tables[0]);

                targetAdapter.Update(targetDs.Tables[0]);
            }

        }

      

There is currently one line in the source that is not in the target. This line is never wrapped. I also tried it with an empty target and nothing passed.

+2


a source to share


2 answers


I know this doesn't directly answer your question, but have you looked at Microsoft Sync Framework ?



It is designed for this kind of thing and does most (if not all) of the donkey work for you.

0


a source


It might be overkill, but you can try Sync Framework from Microsoft



0


a source







All Articles