4
votes

I am currently learning MVVM in WPF. I am creating an application that incorporates Entity Framework using Code First approach. What should be the proper structure of my project?

MVVM has this structure

Views 
ViewModels
Model 

My current plan is to put my POCO into the Model folder. Where should I put the class that inherits from the DbContext class?

2

2 Answers

4
votes

MVVM does not specify a service infrastructure per se. While your POCO domain should remain in the "Model" directory the DbContext should not be known to the MVVM implementation.

In other words there shouldn't be a class that derives from DbContext.

I normally provide that type of functionality through a ViewModelProvider construct that abstracts the "actual" model away from the ViewModel implementation. This lends to easier mocking etc. All concrete viewModel implementations should be "provided" through this abstraction.

0
votes

The Models, Views, and ViewModels buckets are really just layers of your application. Their actual location doesn't matter, so long as the interactions between them don't violate the MVVM pattern.

That said, I tend to follow the pattern set by ASP.NET MVC and the T4Scaffolding NuGet package. After installing that package you can issue the following command.

Scaffold Repository -ModelType Person

This will scaffold two new classes for you based on the Person model class.

  • Models\MyApplicationContext.cs
  • Models\PersonRepository.cs

The first is just a standard DbContext class like you would expect. It is not inteded that your Views or ViewModles will interact directly with this class. The repository class provides an abstraction over the context; this is the one you should pass around between layers. A repository is also much easier to mock than DbContaxt, and could easily be implemented using a totally different technology like WCF Data Services.

Hopefully this answer at least gives you a good place to start.