views:

646

answers:

1

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

+3  A: 

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...

IanR
Interesting. I always thought that model specific validation like say to gender should be in the model but validation at a higher level - stuff that involves multiple properties or other objects should be in the view model. One of my main things I want to do is avoid having to re-surface the customer properties multiple times. It is defined automatically for me in the data model so having to do it again in the model and wire it up then again in the VM to be wired up yet again seems like I'm making work for myself when the database changes. Introspection looks interesting for this.
SteveChadbourne