MVC3 View Model and Entity Framework Model

I don’t know how to explain it, but here it goes ...

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

Problem. Data will be collected / presented using different views, some of which will require address fields, while others will not.

I can create different presentation models, each of which has the necessary validation attributes, and copy the data back and forth between the data model and the view model, but this seems wrong.

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

Thanks for your help, Jimmy

+7
source share
1 answer

First read these questions and their answers:

  • MVC: data models and view models
  • Why two classes, model and domain model?

also this article can help:

In conclusion, I think that in most scenarios it is useful to have a puffy domain model (DM), as well as light weight representation (PM) models associated with it. Therefore, when we want to edit only a small piece of this bold DM, one of our PM will raise his 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 only need to edit the address and phone. Lightweight PM may be as follows:

 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 form 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;} } } 

The juxtaposition between DO and PM is the golden part of this puzzle. Be sure to check out AutoMapper .

+6
source

All Articles