WPF app with static DbContext in ViewModel

c# dbcontext entity-framework-6 mvvm wpf

Question

I'm utilising MVVM, Code-First, and the repository approach to create a WPF application. I need a background activity that handles client webserver requests and adds new data to the database.

The issue is that each ViewModel has an ObservableCollection field that returns Repository. GetObservableCollection(). As a result, each ViewModel has a repository instance that shares the same DbContext, which prevents DbException from occurring when complicated entities are saved. This DbContext is injected from MainViewModel to the VM constructors and has a lengthy lifespan till the end of the app in each repository.

Because I'm using a separate DbContext there (I have to due to concurrent requests), the GUI doesn't refresh when I add new data to the database from the background task:

using (var db = new DbContextManager())
{
    var client = new Client();
    db.Client.Add(client);
    db.SaveChanges();
}

I tried these two approaches:

  1. Create a dispatcher timer in the main view model to update the view models every two seconds. Repository. For each repo, load all. The UI slows every two seconds, however it still functions.
  2. Include adding the entities to Repositories through when adding new data to the database.

    Application.Current.Dispatcher.Invoke ( () => { _clientRepository.Add(client); } );

In this manner, the entities display in the GUI immediately, however there is a tiny latency (when changing the window) and I am unable to adjust the properties of existing instances.

How can I rework this to enable interaction with things from the GUI and the background? How should repository and MVVM be combined properly?

1
1
3/25/2017 9:10:16 AM

Popular Answer

ZZZ_tmp
0
3/26/2017 10:37:14 AM


Related Questions





Related

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