Wednesday, March 4, 2009

Basics of Merging Datasets

Hi, Friends ,
This is my first blog. so please ignore mistakes if i have done in this article.

So When i got this task mean merging the datasets and Update Database , i got nervous but now i m feeling its too easy.

Now Explaning with follwing code,

For Create Dataset 1

SqlConnection con = new SqlConnection(connString);
SqlDataAdapter sda = new SqlDataAdapter("Select * from Users", con);
DataSet Ds = new DataSet();
SqlCommandBuilder sbd = new SqlCommandBuilder(sda);
sbd.ConflictOption = ConflictOption.OverwriteChanges;

sda.AcceptChangesDuringFill = false; //This will maintain Row State-Added

sda.AcceptChangesDuringUpdate = false; //This will maintain Row State-Added

sda.ContinueUpdateOnError = true; // This will contineu update source

sda.FillLoadOption = LoadOption.OverwriteChanges;
//this is must to get Row State Unchanged

sda.MissingSchemaAction = MissingSchemaAction.AddWithKey;
// To get Primary key & others constraint


sda.Fill(Ds); //finally fill the Dataset1


For Create Dataset 2

SqlConnection con1 = new SqlConnection(connString2)
SqlDataAdapter sda1 = new SqlDataAdapter("Select * from Users", con1);
DataSet Ds1 = new DataSet();
sda1.AcceptChangesDuringFill = false;
sda1.AcceptChangesDuringUpdate = false;

sda1.FillLoadOption = LoadOption.Upsert;//This will fill rows with State - Added

SqlCommandBuilder sbd1 = new SqlCommandBuilder(sda1);
sbd1.ConflictOption = ConflictOption.OverwriteChanges;
sda1.ContinueUpdateOnError = true;
sda1.MissingSchemaAction = MissingSchemaAction.AddWithKey;

sda1.Fill(Ds1); //finally fill the Dataset 2

//Ds1.AcceptChanges(); Do not Write this Coz this will change row state

Ds.Merge(Ds1, false, MissingSchemaAction.AddWithKey);
sda.Update(Ds);

In this Code no where is code for Row state but whole code depend on Row state.
So be carefull on Row State

No comments:

Post a Comment