简体   繁体   中英

add only changed rows of the DataSet to the Database table

In my project, I want to update the database table by using C#. The data of Database table is also in DataSet. Here whenever I change DataSet row values and then click on a button then the Database table should get updated.

At present, I am deleting all the database table (DELETE query) and then again adding the DataSet data to it (INSERT query). which is really horrible. (I realized this later)

How to add the rows of DataSet to the Database table which have been changed? I have no idea where to start from. I tried giving query "Insert" which is doubling the data in Database table. or else is there any alternative approach? Please help.

Do you mean something like this?

protected void Page_Load(object sender, EventArgs e)
 {
  DataTable dtDocOperations = new DataTable();
  dtDocOperations.Columns.Add("ButtonRole");
  dtDocOperations.Columns.Add("OperattionCode");
  dtDocOperations.Rows.Add(new Object[] { "MR", "V" });
  dtDocOperations.Rows.Add(new Object[] { "MR", "A" });
  dtDocOperations.Rows.Add(new Object[] { "MR", "R" });
  Session["DocOperattions"] = dtDocOperations;
  dtDocOperations.AcceptChanges(); // once AcceptChanges called then you can get the modified rows

  dtDocOperations.Rows[0]["ButtonRole"] = "mr1";
  DataTable dt = dtDocOperations.GetChanges(DataRowState.Modified);
 }

With

dtDocOperations.AcceptChanges();

and

 DataTable dt = dtDocOperations.GetChanges(DataRowState.Modified);

You can fill a Datatable with the modified rows

Have a look at method DataSet.AcceptChanges().

Here is the msdn article for detail

http://msdn.microsoft.com/en-us/library/system.data.dataset.acceptchanges.aspx

Several things to note:
1. You would probably like to use an ORM: Entity Framework , NHibernate , Dapper are some solutions to consider.
2. If you're using Gridview or some other controls, they can usually handle this case automatically for a simple databindings.
3. You can always manually run query with each primary key to check if ID exists. and if it is then run update, if not, run insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM