Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Entity Framework and MVVM to play nicely together?

I'm would like to use both EF and MVVM and am trying to see how they fit together. I can't find much in the way of examples so hope you guys can answer a few questions.

Let's say I have a single table in a database called Customer. I run the EF designer and get a data model.

The next step is to run some linq to get data out of the data model. Let's create a new class called CustomerRepository to do this.

Now I'm guessing the Model would call CustomerRepository.GetCustomers to get a list of customers.

Here is my question - CustomerModel has a list of customer objects that were defined by EF in the data model. How do I add validation attributes or any kind of validation to it?

There just seems to be a bit of a disconnect between EF and MVVM. I'm sure some of you have hit this before - any ideas? Any better ways of approaching this?

Cheers

Steve

like image 881
Steve Chadbourne Avatar asked Jan 02 '10 01:01

Steve Chadbourne


1 Answers

The validation, the business rules, the presentation of your Customer object should live in the ViewModel that will serve as a controller or presenter for your View.

In terms of how to create that ViewModel, you have a couple of options:

  1. Include the Model as a property of the VM, and pass the model instance into the VM's constructor. You can then expose the Customer's properties and just wire them through to the underlying Model's corresponding properties.
  2. Generate a ViewModel using T4 templates and Reflection (or preferably Introspection) to 'read' the Model, and generate the properties that will map directly to it.

Now you can add custom validation rules to the VM, such that when the appropriate command is sent from the View you can perform your business rules, and if appropriate you can update the Model using EF's API to persist those changes back to the database...

like image 153
kiwipom Avatar answered Oct 23 '22 14:10

kiwipom