更改没有保存回数据库
问题描述:
我想连接到我的NorthwindDataSet,当用户单击按钮时,我希望将数据保存回数据库。当我运行下面的代码时,我没有得到任何错误,但数据没有保存。我想我正确连接到DataSet,我不知道为什么这不会挽回。更改没有保存回数据库
NorthwindDataSetTableAdapters.CustomersTableAdapter north = new NorthwindDataSetTableAdapters.CustomersTableAdapter();
NorthwindDataSet.CustomersDataTable northtable = north.GetData();
NorthwindDataSet northwindDataSet1 = new NorthwindDataSet();
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();
newCustomersRow.CustomerID = "5";
newCustomersRow.CompanyName = "Alfreds Futterkiste";
northwindDataSet1.Customers.Rows.Add(newCustomersRow);
northwindDataSet1.Customers.AcceptChanges();
答
您不仅需要通过AcceptChanges方法提交更改,还需要在表适配器上使用Update方法。
在你的情况下,它看起来就像这样:
north.update(northwindDataSet1.Customers);
northwindDataSet1.Customers.AcceptChanges();
接受更改不会提交数据到数据库。更新确实。
+0
它看起来像你正试图设置主键,所以默认情况下,框架阻止你从此(因为PK应该是自动生成的)。我想你将不得不改变INSERT查询和参数。当然,考虑到在DB中没有定义标识字段,这又会阻止你在数据库级更新PK列。 – 2013-05-10 12:05:36
我已经使用过这些东西了,但DataSet和DataAdapter之间的连接是什么?我期望CustomersTableAdapter实例通过Update()或自定义方法进行更新。 – 2013-05-10 11:48:47
您是否需要在TableAdapter上调用Update方法? – 2013-05-10 11:48:58