将WPF控件绑定到EF数据

时间:2014-05-28 08:50:14

标签: .net wpf entity-framework binding

我正在学习一些关于使用EF将WPF简单控件绑定到数据的示例教程。

具体来说,这些教程使用EF 3.5和Visual Studio 2008 SP1几年了。

在我的情况下,我使用的是Visual Studio 2012和EF 5,虽然我的目标是.NET Runtime 4.0。

在一个示例中,“我如何:使用实体框架构建WPF数据输入表单?”:

http://msdn.microsoft.com/en-US/vstudio/dd776540.aspx

我尝试使用我的环境重现教程(在VB.NET和C#中),我遇到了以下代码行的问题:

Me.view = CType(customerSource.View, BindingListCollectionView)

此行在我的情况下抛出以下运行时异常:

“无法将类型为'System.Windows.Data.ListCollectionView'的对象强制转换为'System.Windows.Data.BindingListCollectionView'”。

在我自己制作的另一个例子中(这次是C#)。

我在WPF代码窗口中有以下模块级别的变量:

private BindingListCollectionView customerView;
private NcrSupportEntities _context ;
private List<Customer> _list;

在加载的事件中,我初始化变量:

_list = _context.Customers.ToList();
this.customerView = new BindingListCollectionView( new BindingList<Customer>(_list));
this.DataContext = customerView;

这次我没有遇到运行时错误,但BindingListCollectionView方法没有按预期工作。

例如,如果我想添加新记录,则以下代码无法正常工作:

Customer customer = (Customer)customerView.AddNew();

customer.CustomerName = "<new>";
customer.Address = "";
this.customerView.CommitNew();

this.customerView.Refresh();
this.customerView.MoveCurrentToLast();

UI控件正确显示但是当我对绑定字段进行更新并调用数据上下文“SaveChanges”方法时,新记录不会保存回数据库。显然,上下文没有跟踪UI级别所做的更改。

为了完成这项工作,我必须创建一个新的客户对象并手动将其添加到Customers实体。

调用BindingListCollectionView的RemoveAt方法也不能用于删除记录。相反,我还必须在调用“SaveChanges”之前手动从数据上下文中删除记录。

我不确定我做错了什么?

请不要回答我应该如何使用MVVM范例,我很清楚,我只是想了解我的简单绑定示例中发生了什么。

0 个答案:

没有答案