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.
Entity Framework and by extension
DbContext
supports theUnitOfWork
design pattern. The idea being that you keep your logical "transactions" separated. Because of this, you will usually want to have each portion or feature of your application deal with its ownDbContext
instance.The way you can think about it is that the
DbContext
holds a local copy of whatever it pulled from the database and tracks all changes made to the local data by the user. When you're ready, you tell it to push the required changes back to the database in one go.For your question about pit-falls and perils; The Entity Framework uses what's called optimistic concurrency by default. This means that when saving the local changes back to the database, concurrency isn't checked at all. Whatever you had in your local DbContext is sent back to the database regardless of whether another user or another context in your application changed it. An excellent article explaining that and how to change the behaviour can be found here: http://msdn.microsoft.com/en-us/library/bb738618.aspx