asp.net mvc 2 - ViewModel Redudancy Clarificaion -
i reading viewmodel , advantages. able understand why needed, question have if have 2 classes same object(ie. person class), doesn't make code redundant ? no make future changes little difficult since need make sure base class model , view model has same number of properties right ? instance let's have table called person has
- id
- name
- color
i creating hbm creating mapping nhibernate. have following model class
public class person { public int id {get;set;} public string name {get;set;} public string color {get;set;} } if correct, view model class should
public class personviewmodel { [displayname("full name")] public string name {get;set;} [displayname("favourite color")] public string color {get;set;} } first, have 2 classess referring same object in db. though 1 class used db purposes , other 1 used view purposes, still have 2 class same meta data. secondly, if introduce new field in db, need add in 3 places, base model class, view model class , hbm file.
please correct me if wrong, how can termed code optimization or best practice.
it depends on approach wish take, expose model directly property of view model avoid violating dry principle. however, violate law of demeter have balance this, views more tightly coupled domain model.
also, in terms of validation, if expose model directly need careful property exposed set end user, if don't use property directly in view. more have different validation requirements per view, in case validation concern of view model.
that's why general best practice not expose domain models directly view. can use frameworks such automapper reduce data transfer plumbing code between layers.
Comments
Post a Comment