I'm developing WPF application using MVVM, Code-First and the repository pattern. I need to have a background task, which processes webserver requests from clients and saves new data into database.
The problem is each ViewModel has a property (ObservableCollection), which gets Repository.GetObservableCollection(). So each ViewModel has a repository instance, which has the same DbContext (so I don't get DbException when saving complex entities). This DbContext is long-living until the end of app in each repo and is injected from MainViewModel to the contructors of VMs.
When I save new data to the database from the background task, the GUI doesn't update, because I'm using different DbContext there (I have to due to concurrent requests):
using (var db = new DbContextManager())
{
var client = new Client();
db.Client.Add(client);
db.SaveChanges();
}
There are two ways, which I tried:
- Set up DispatcherTimer in MainViewModel to update ViewModels every 2secs using ViewModel.Repository.LoadAll for each repo. This lags my UI every 2secs, but it works.
When saving new data into the DB, also add the entities to Repositories via.
Application.Current.Dispatcher.Invoke ( () => { _clientRepository.Add(client); } );
That way, the entities appear in GUI immidiately, but there's also slight lag (when moving window) and I can't update existing entity's property.
The question is how can I refactor this to allow both GUI and background interaction with entities. How to properly combine repository and MVVM?