Sunday 15 June 2014

c# - making concrete object to type "Object" loses properties -



c# - making concrete object to type "Object" loses properties -

if have next class

person { string firstname {get;set;} string lastname {get;set;} }

and in class next

otherclass { list<person> personlist = new list<person(/*10 people in here*/); list<object> personobjectlist = new list<object>(); foreach (person p in personlist) { personobjectlist.add(p); } }

then seek

personobjectlist[0].firstname;

why not recognized object has firstname property? didn't realize changing type of object makes lose properties.

thank you

you have 2 main choices. in order of suggest.. are:

create view models per view. these objects in ui layer represent specific info individual views. map domain models view models in controller. libraries automapper , valueinjecter can help remove lot of plumbing code in regard. careful not introduce business logic mappings.

this has 2 main benefits:

your view can utilize typed view models instead of casting everywhere your view models , domain models can evolve independently

that sec point very important. when allow views utilize domain models directly, fall lot of big traps. biggest start using html.hiddenfor (<input type="hidden"/>) everywhere persist info between pages - , very becomes nightmare deal with.

also, having separate view models allows models evolve independently. domain model may have properties relating business need - view model can contain properties relate purely ui concerns. things ui level validation, aggregation properties (such fullname in view model instead of firstname + surname). flexibility really nice have.

secondly, against have said above - can place @using directive @ top of view include namespace objects are. allows utilize models in view.

..i suggest investigate first alternative provided though. you'll sense improve later on in project.

c#

No comments:

Post a Comment