MVVM with Entity Framework

I am currently studying MVVM in WPF. I am creating an application that includes the Entity Framework using the 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 in the Model folder. Where should I put a class that inherits from the DbContext class?

+4
source share
2 answers

MVVM does not define the service infrastructure as such. Although your POCO domain should remain in the Model directory, DbContext should not be known to the MVVM implementation.

In other words, there should not be a class that derives from DbContext.

I usually provide this type of functionality through the ViewModelProvider construct, which abstracts the "actual" model from the ViewModel implementation. This makes it easier to ridicule, etc. All concrete representations. Model implementations should be "provided" through this abstraction.

+4
source

The encodings of models, views, and ViewModels are really just layers of your application. Their actual location does not matter if the interaction between them does not violate the MVVM pattern.

However, I try to follow the pattern set by ASP.NET MVC and the T4Scaffolding NuGet package. After installing this package, you can run the following command.

 Scaffold Repository -ModelType Person 

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

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

The first is just the standard DbContext class, as you would expect. It is not intended that your Views or ViewModles interact directly with this class. The repository class provides an abstraction by context; this is the one you have to go between layers. The repository is also much easier to trick than DbContaxt, and it can be easily implemented using a completely different technology, such as WCF data services.

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

0
source

All Articles