Should I use the same context everywhere when using the Repository Pattern with Entity Framework 3.5 and MVVM?

c# entity-framework mvvm repository-pattern wpf


I am developing a Database File System. I am using -

  1. .Net framework 3.5
  2. Entity Framework 3.5
  3. WPF with MVVM pattern

The project spans across multiple assemblies each using same model.

One assembly,let's call it a "server", only adds data to the database using EF i.e. same model.Other assemblies (including the UI) both reads and writes the data.The changes made by server should immediately reflect in other assemblies.

The database contains self referencing tables where each entity can have single OR no parent and (may be) some children. I want to use repository pattern which can also provide some mechanism to handle this hierarchical nature.

I have already done reading on this on Code Project. It shares the same context(entities) everywhere.

My question is - Should I share the same context everywhere? What are the advantages and disadvantages of doing that?

11/16/2017 7:23:39 PM

Accepted Answer

The BookLibrary sample of the WPF Application Framework (WAF) shows how you can use WPF MVVM and Entity Framework together. It separates the layers into individual assemblies.

Maybe that’s what you are looking for.

4/15/2010 5:49:42 PM

Popular Answer

From what I understand the objectcontext should be used when needed and then thrown away. so you probably want to wrapped it in a unit of work interface, along with a unit of work factory to create the unit of works when needed.

As far as your question about the entities reflecting the changes across "assemblies". The thing is your objects do not live exists in assemblies. They exists in memory.

So in order to have the changes reflected across the application you either have to have a maintain a reference to the same object across your entire app. Or you could implement a notification system so when an entity or a collection of entities is changed, the other side of your app notices and refreshes the data.

The downside to keeping a single context alive is that every time you do queries on the object context it grows with the entities loaded from the db. In a long running app this translates into a lot of memory consumption.

The downside to using a brand new context every time is that any call to the repo gives you a fresh copy of data. Now this should not be an issue since since the repo's only concern should be saving/loading data; not handling concurrency or data duplication across layers

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow