JConnell
JConnell

Reputation: 93

MVC3 View Model versus Entity Framework Model

Not sure how to explain this, but here goes...

I've built a code first data model using EF 4.3. One of classes, "Address" contains typical address data, street, city, state, etc. Other classes in the model contain instances of the "Address" class.

The problem. The data will be gathered/presented using different views, some of which will require the address fields, others that will not.

I can build different view models, each having the necessary validation attributes, and copy the data back and forth between data model and view model but that seems wrong.

What am I missing? There has to be a smarter way to do this.

Thanks for your help, Jimmy

Upvotes: 7

Views: 2852

Answers (1)

Tohid
Tohid

Reputation: 6679

First read these questions and their answers:

also this article could help:

In conclusion, I think in most scenarios it's helpful to have a chubby domain model (DM) but light weight presentation models (PM) related to it. So when we want to edit only a small chunk of that fat DM, one of our PMs will raise its hand.

Imagine this class in DM:

namespace DomainModels
{
    public class Person
    {
         public int ID { get; set; }
         public string FirstName { get; set; }
         public string MiddleName { get; set; }
         public string LastName { get; set; }
         public DateTime? DoB { get; set; }
         public MyAddressDM Address { get; set; }
         public string Phone { get; set; }
         public IEnumerable<MyCarModel> Cars { get; set; }
         //etc.
     }
}

Now imagine that in one view we need to edit only Address and Phone. A light weight PM could be like:

namesapce PresentationModels
{
     public PersonAddressPhone
     {
         public int ID { get; set;}
         public string FullName { get; set;}
         public string AddressSteet { get; set; }
         public string AddressCity { get; set; }
         public string AddressState { get; set; }
         public string AddressZipCode { get; set; }
         public string Phone { get; set; }
     }
}

and in another view we need to add/remove cars for a person:

namesapce PresentationModels
{
     public PersonCars
     {
         public int ID { get; set;}
         public string FullName { get; set;}
         public IEnumerable<PMCar> Cars { get; set;}
     }
}

Mapping between DO and PM is the golden piece of this puzzle. Be sure to take a look at AutoMapper.

Upvotes: 6

Related Questions