I am learning the Entity Framework and using it in an MVVM app where each ViewModel works with the DbContext for Data Access. Disclaimer: In a real application I know the ViewModel shouldn't interact directly with the Data Access Layer.
Given that each ViewModel is there to monitor and manipulate the state of the View by maintaining relationships with the Models themselves, I began to wonder about the implications of spinning up multiple DbContext objects, and if something like a DBContext is best left as a singleton - to which I quickly found the answer was "NO". So if the consensus is to have an instance for each use (as in the case with multiple ViewModels, or what-have-you) I still havent seen where any one mentions the potential issues with having this.
To elaborate, lets say I have two ViewModels and in each I create a Context (TestContext
inherits from DbContext
) to maintain the Data Access activities during the lifetime of each ViewModel:
public class MainWindowViewModel : ViewModelBase
{
private TestContext db = new TestContext();
... other code follows (properties methods etc...)...
}
public class TestViewModel: ViewModelBase
{
private TestContext db = new TestContext();
... other code follows (properties methods etc...)...
}
Are there any pitfalls with having a context in each class that can consume it?
One such thought that taunts me is if it's possible to have either context be out of sync with the other, such that one ViewModel has more recent data than the other by way of its context being more "up-to-date". Things like this I am interested in knowing.
Thanks.
EDIT
I dont hope to discover / cover every situation as that would be unique TO the situation against which one is coding. I just want to know if there are any "up-front" or obvious perils that I am unaware of being new to the subject.