如何在实体框架中分配上下文并刷新它?
我创建了一个新的实体对象并将其绑定到另一个窗口(编辑窗口)中的控件。修改并保存后,我将一个新的实体对象分配到主窗口中的实体对象中。旧的实体对象绑定到数据网格中,现在我希望数据网格显示我修改和保存的数据。
ObjectContext.Refresh 方法(RefreshMode,对象) 似乎是我想要的但我不知道如何正确使用它。
简而言之:
我有一个主窗口,其中数据网格显示表的全部数据。用户可以选择一行并在编辑窗口中对其进行编辑。保存后,数据网格应显示已修改的内容。
I created a new entity object and bound it to controls in another window (edit window). After modifying and saving I assigned a new entity object into the one in the main window. The old entity object is bound into a datagrid, now I want the datagrid to display the data that I had modified and saved.
ObjectContext.Refresh Method (RefreshMode, Object) seems to be what I want but I don't know how to use it correctly.
In short :
I have a main window with datagrid displaying the whole data of the table. Users can pick one row and edit it in a edit window. After saving, the datagrid should display what has been modified.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里最好的选择是使用
ObservableCollection
作为数据网格的数据源而不是查询。并查看在
Customer
类中实现INotifyPropertyChanged
接口。ObservableCollection
最初由数据库查询填充。用户对ObservableCollection
中的元素进行更改,完成后,您只需触发将更改传输到您最初获取Customer
对象列表的位置。客户集合和单个客户对象(如果存在于数据网格中)都将自动为您更新。
编辑
我必须承认,我现在有点急于提供任何代码,但是这是一篇非常好的文章,解释了如何使用
ObservableCollections
和实现的类INotifyPropertyChanged
。它还具有代码示例,虽然在 VB.NET 中,但应该为您提供足够的入门想法。实际上,您将代码分为不同的 UI 层(视图)、业务逻辑层(视图模型)和数据层(实体框架所在的模型)。
您将数据网格绑定到 Customers 类中的 ObservableCollection 类型属性,并且您的编辑客户窗口绑定为 Customer 类的实例。
Your best bet here is to use an
ObservableCollection
as your data source for the datagrid instead of the query.And look at implementing
INotifyPropertyChanged
interface in yourCustomer
class.The
ObservableCollection
is initially populated by the database query. User changes are made to elements within theObservableCollection
and once complete you then just need to trigger transferring the changes to wherever you originally obtained your list ofCustomer
objectsBy doing this changes made both to the collection of Customers and to individual Customer objects (if present within the datagrid) will be automatically updated for you.
edit
I must admit that I'm a bit rushed to offer up any code at the moment, but here's a pretty good article that explains how to use
ObservableCollections
and classes that implementINotifyPropertyChanged
. It also has code examples, which although in VB.NET should give you enough of an idea to get started.In effect you separate your code into distinct layers UI (View), business logic (View Model) and data layer (Model where your entity framework resides).
You bnd your datagrid to the ObservableCollection type property in your Customers class and your edit csutomer window is bound to as instance of your Customer class.