[英]WPF Entity Framework binding
I'm following this tutorial and trying to implement Data Binding
using an Editable ComboBox
instead of the DataGrid
demonstrated in the tutorial. 我正在关注本教程,并尝试使用
Editable ComboBox
而不是本教程中演示的DataGrid
来实现Data Binding
。
The only problem I encounter is that I cannot add a new item to the DB that way. 我遇到的唯一问题是我无法以这种方式向数据库添加新项目。
This is how I load the data: 这就是我加载数据的方式:
private DbEntities db = new DbEntities();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
CollectionViewSource productViewSource =
((CollectionViewSource)(this.FindResource("productViewSource")));
db.Product.Load();
productViewSource.Source = db.Product.Local;
}
and in a Button_Click
event I tried the following methods without success: 在
Button_Click
事件中,我尝试了以下方法,但Button_Click
成功:
db.Product.Add(new Product() { ProductCode = "", Description = "" });
db.Product.Load();
productViewSource.Source = db.Product.Local;
productComboBox.Items.Refresh();
productViewSource.View.MoveCurrentToLast();
and: 和:
ListCollectionView lcv = productComboBox.ItemsSource as ListCollectionView;
lcv.AddNewItem(new Product() { ProductCode = "", Description = "" });
lcv.MoveCurrentToLast();
Using the DataGrid
provided by the default DataSource
template works as expected by adding a new item on the empty bottom row of the grid. 通过在
DataGrid
底部空白行中添加新项目,可以使用默认DataSource
模板提供的DataGrid
达到预期的效果。
Please advise. 请指教。
You don't seem to be calling SaveChanges
on your data context object anywhere. 您似乎没有在任何地方对数据上下文对象调用
SaveChanges
。 I would have thought that your code should look more like this: 我本以为您的代码应该更像这样:
db.Product.Add(new Product() { ProductCode = "", Description = "" });
db.SaveChanges();
Please see the Add/Attach and Entity States page on MSDN for more help with adding entities in the Entity Framework. 请参阅MSDN上的“ 添加/附加和实体状态”页面,以获取有关在实体框架中添加实体的更多帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.