Data Binding to Entity Framework in WPF – How to Implement

designentity-frameworkwpf

Is it good to use databinding to Entity Framework's Entity in WPF?

I created a singleton entity framework context:

  1. To have only one connection and it won't open and close all the time.
  2. So I can pass the Entity around to any class, and can modify the Entity and make changes to the database.

All ViewModels getting the entity out from the same Context and databinding to the View saves me time from mapping new object, but now I imagine there is problem in not using the newest Context:

A ViewModel databinding to a Entity, then someone else updated the data. The ViewModel will still display the old data, because the Context is never being dispose to refresh.

I always create new Context and then dispose of it. If I want to pass the Entity around, then there will be conflicts between Context and Entity.

What is the suggested way of doing this ?

Best Answer

The suggested way is don't do it -- results are unpredictable to the point of being dangerous to your data. You should not give the view direct access to the database. Results are unpredictable.

First, the nature of both databinding and the modern fancy ORMs is pretty heavy reflection and other similar stunts. Oftentimes things just don't work or just don't get updated in the way that the ORM expects so there are very odd bugs to track down. Second, those DbContexts are pretty stateful and there can be lots of complications when newing them up and passing in objects. Third issue is the potential for the SELECT N+1 sort of performance issues -- if you cut off database access then your view can't reach back to the database to do a sub-select for every single customer you put in the list, for instance. Finally, for non-trivial applications, one rarely sees scenarios where the front-end views want to talk to an object shaped like the back-end entities.