Thiago Romam
Thiago Romam

Reputation: 439

WPF + EF: binding an entity and track changes from different contexts

I have a WPF application using Entity Framework and two views:

Considering the following scenario:

  1. The ProductListView is opened: a DbContext is instantiated, the product list is filled and the DbContext is closed.
  2. The user selects a product and click in the edit button.
  3. The ProductEditView is opened: a DbContext is instantiated, the product is loaded by its ID, the fields are filled and the DbContext is closed.
  4. The user changes the fields and click in the save button: a DbContext is instantiated, the product is loaded by its ID, the changes are applied and the DbContext is closed.

How the selected product's bindings in the product list would be notified?


In a memory context:

  1. I just pass the product object from the ProductListView to the ProductEditView,
  2. I bind the fields to the ProductEditViewModel properties,
  3. When the save button is clicked, I update the product reference.

Since it's the same reference I don't need to do anything to the product list be updated.


I don't see how I could do the same thing using EF context.

Any sugestions?

Upvotes: 0

Views: 442

Answers (1)

Michal Ciechan
Michal Ciechan

Reputation: 13898

In EF Context, I would suggest you keep the DbContext across all 4 actions. This will save you a lot of hastle.

Not unless your products data is very large and you only retrieve the title and id lets say in initial list fetch, then keep the same DbContext open from time they open EditView till they close it. And if they save, EF will find the changes.

It finds changes by comparing the values it retrieved from database, to the values currently set to the entity. By closing the entity context, you are getting rid of the OriginalValues.

Upvotes: 1

Related Questions