从 WPF Datagrid 保存对 SQL Server 数据库的更改
我正在使用 WPF 数据网格来显示 SQL Server 数据库中的内容。数据网格中的内容绑定到数据库中的视图。我在由以下内容加载的窗口上填充数据网格:
this.myAccountantDBDataSet = MyAccountant
.MyAccountantDBDataSet(this.FindResource("myAccountantDBDataSet");
// Load data into the table AccountData.
this.accountDataAdapter = new MyAccountant
.MyAccountantDBDataSetTableAdapters.AccountDataTableAdapter();
this.accountDataAdapter.Fill(myAccountantDBDataSet.AccountData);
System.Windows.Data.CollectionViewSource accountDataViewSource =
(System.Windows.Data.CollectionViewSource)
this.FindResource("accountDataViewSource");
accountDataViewSource.View.MoveCurrentToFirst();
我想知道的是如何将更新、插入和删除保存回数据库,因为我在数据网格中显示的是一个视图。数据库表和视图如下所示:
I am using a WPF datagrid to display my contents in a SQL Server Database. The contents in the datagrid are binded to a view in the database. I populate the datagrid on window loaded by the following:
this.myAccountantDBDataSet = MyAccountant
.MyAccountantDBDataSet(this.FindResource("myAccountantDBDataSet");
// Load data into the table AccountData.
this.accountDataAdapter = new MyAccountant
.MyAccountantDBDataSetTableAdapters.AccountDataTableAdapter();
this.accountDataAdapter.Fill(myAccountantDBDataSet.AccountData);
System.Windows.Data.CollectionViewSource accountDataViewSource =
(System.Windows.Data.CollectionViewSource)
this.FindResource("accountDataViewSource");
accountDataViewSource.View.MoveCurrentToFirst();
What I am wondering, is how to save updates, inserts, and deletions back to the database since what I am showing in the datagrid is a view. The database table and views looks like this:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新将起作用,因为视图中的字段与基础表中的字段一一对应,因此 Sql Server 将能够将视图中的更新解析回表(甚至
AccountType
)。插入将不起作用,因为无法设置
Account.AccountTypeId
并且我认为它是必填字段。删除将不起作用,因为 Sql Server 无法判断您要删除哪个表中的哪条记录。
我认为在这种情况下,您也可以使用
Accounts
记录并在DataGridComboBoxColumn
具有AccountData
作为数据源,显示AccountData.AccountType
并绑定到Account.AccountTypeId
。Updates will work, because the fields in the view map 1:1 to fields in the underlying tables, so Sql Server will be able to resolve updates in the view back to the tables (even
AccountType
).Inserts will not work because
Account.AccountTypeId
can not be set and I assume that it is a mandatory field.Deletes will not work, because Sql Server cannot tell which record in which table you are trying to delete.
I think in this case, you can just as well work with
Accounts
records and showAccountTypeId
in aDataGridComboBoxColumn
that hasAccountData
as datasource, displaysAccountData.AccountType
and binds toAccount.AccountTypeId
.