Reputation: 53
I'm a newbie with WPF/MVVM/Entity Framework and it's a lot of concepts to handle simultaneously. I'm creating a WPF app with only one main View, which is splitted in 2 parts : 1 UserControl for a Master view of my data, another userControl for the detailed view. All data is stored in database generated via Entity Framework entity model.
So far I managed to do what I wanted (I use MVVM light) : databinding, commands, eventToCommand... I use following architecture in 1 VS project : 1 folder for Views, 1 for ViewModels, and 1 for Entities definition.
I pass data from master to detail userControl using MVVM Light Messaging, and when I try to update one entity, I encountered exception telling me that I can't update because I try to update one object linked to an ObjectContext (declared in MasterViewModel) with one object from another one (declared in DetailedViewModel)
How can I share EF ObjectContext between ViewModels? I read some stuff about repositories or UnitOfWork but I didn't really manage to see how I could use it in my case.
Subsidiary question : what's the best practice to access entities with EF and a n-tier app? Is the repository the answer? COnsidering the fact that classes already exists, should I have a "Model" folder in my solution architecture?
Upvotes: 3
Views: 1009
Reputation: 39898
The answer is in the two design patterns you mention.
A Repository is a design pattern that helps you to create a single access point to your data. For example a CustomerRepository which has functions like GetById(int customerId)
, Update(Customer customer)
, Delete(Customer customer)
and Add(Customer customer)
and, depending on your specific flavor of implementing the pattern, other more specific functions for handling data that involves a customer.
In a regular application you would have a couple of Repositories that will give you access to different kinds of data. In a business function you would then use some of those repositories to build functionality.
Then the UnitOfWork pattern comes around, because this helps you to group a set of related operations. The Unit of Work keeps track of the changes until you save them to the database as a whole. (The ObjectContext in EF is an implementation of the UoW pattern)
In your example showing a master form and then loading and updating the details of one of those items, is a group of related operations that you want to update together.
This means that you should use one UoW for the master and the details view.
This is nice article which shows the basics of how an implementation of the Repository and UoW patterns could look like when using EF.
Here you can find an explanation of the Repository pattern and here of the Unit Of Work (those references are both from Patterns of Enterprise Applications, a really good book if you want to learn more)
Upvotes: 5