简体   繁体   English

仅将数据集的更改行添加到数据库表

[英]add only changed rows of the DataSet to the Database table

In my project, I want to update the database table by using C#. 在我的项目中,我想使用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. 在这里,每当我更改DataSet行值,然后单击一个按钮时,数据库表就应该更新。

At present, I am deleting all the database table (DELETE query) and then again adding the DataSet data to it (INSERT query). 目前,我正在删除所有数据库表(DELETE查询),然后再次向其中添加DataSet数据(INSERT查询)。 which is really horrible. 这真的很可怕。 (I realized this later) (我稍后意识到了这一点)

How to add the rows of DataSet to the Database table which have been changed? 如何将已更改的DataSet行添加到数据库表? I have no idea where to start from. 我不知道从哪里开始。 I tried giving query "Insert" which is doubling the data in Database table. 我尝试提供查询“ Insert”,这使数据库表中的数据加倍。 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(). 看一下DataSet.AcceptChanges()方法。

Here is the msdn article for detail 这是msdn文章的详细信息

http://msdn.microsoft.com/en-us/library/system.data.dataset.acceptchanges.aspx http://msdn.microsoft.com/zh-CN/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. 1.您可能想使用ORM: 实体框架NHibernateDapper是要考虑的一些解决方案。
2. If you're using Gridview or some other controls, they can usually handle this case automatically for a simple databindings. 2.如果您使用的是Gridview或其他控件,它们通常可以为简单的数据绑定自动处理这种情况。
3. You can always manually run query with each primary key to check if ID exists. 3.您始终可以使用每个主键手动运行查询以检查ID是否存在。 and if it is then run update, if not, run insert. 如果是,则运行update,如果不是,则运行insert。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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