c# - MVC5 Custom View Model, Get Changes, Update Database -
i have complex object i've broken down viewmodel form. i'll illustrate sample of structure number of fields around 60 total 6 different entities intermingled.
//viewmodel
public class someviewmodel { public tabone tabone {get;set;} public tabtwo tabtwo {get;set;} public someviewmodel(complexobject co) { this.tabone = new tabone { name = co.name, value = co.value}; this.tabtwo = new tabtwo { name = co.name, = co.another }; } }
all works fine , controller view
//controller
[httppost] public actionresult update(someviewmodel vm) { //todo: 1. know properties in viewmodel changed auditing //todo: 2. update changed ef entities in database. }
before sending viewmodel view cache original value in session object , use reflection compare two. it's drawn out , i'll have ton of work changes. there better way??
the viewmodel different structure ef models, it's bunch of custom mapping need done update correct entities. i'd avoid because of number of fields. there better way?
ok, not sure if need understood:
you can original , current values this:
using (var dbctx = new yourdbentities()) { var yourentity = dbctx.yourentity.find(1); var entry = dbctx.entry(yourentity); foreach (var propertyname in entry.currentvalues.propertynames ) { console.writeline("property name: {0}", propertyname); var originalval = entry.originalvalues[propertyname]; console.writeline("original value: {0}", originalval); var currentval = entry.currentvalues[propertyname]; console.writeline("current value: {0}", currentval); } }
for mapping viewmodels ef models can use automapper, can easy as:
automapper.mapper.createmap<book, bookviewmodel>(); var model = automapper.mapper.map<bookviewmodel>(book);
edit: ok, if need manually, can use following method mapping objects:
public static void mapobjects( object source, object destiny) { var modelpropertiesname = new hashset<string>(source.gettype().getproperties().select(x => x.name)); var entityproperties = destiny.gettype().getproperties(); var propertylist = entityproperties.where(p => modelpropertiesname.contains(p.name)) .tolist(); foreach (var prop in propertylist) { var modelproperty = source.gettype().getproperty(prop.name); var value = modelproperty.getvalue(source); prop.setvalue(destiny, value, null); } }
you need pass destiny object , source map properties.
Comments
Post a Comment