Extensions and Reflections and Generics oh my!
|Copyright - https://www.flickr.com/photos/dcwriterdawn/|
I created two extension methods, one which saves model properties to a Dictionary and the other which applies data from a Dictionary and overwrites properties of the model.
The extension method for Getting the properties is called GetModelValues and the other method is ValuesToModel.
Both extensions are defined as a type of T where T is defined as an Interface. This is to ensure that by simply adding a interface to an existing Model class only Model classes would have these extensions.
Originally I used reflection to read and write to the model, but in this article I describe how I changed the approach to using Generics and Delegates to create a more strongly typed implementation.
The original code required you to decorate the models properties you wanted persist using a special attribute. The replacement code is mapped more declaratively.
The complete article and sample code is located at codeproject.com
For those of you looking for the answer to the extra credit, here is what I did.
Dictionary<string, string> pass_this_in = new Dictionary<string, string>();
pass_this_in.Add("name", "Pass this in");
ViewModel2015.ValuesToModel((deleg, dict) =>
deleg.name = dict[nameof(deleg.name)];
deleg.currentdate = DateTime.Parse(dict[nameof(deleg.currentdate)]);
deleg.age = int.Parse(dict[nameof(deleg.age)]);
//ViewModel2015.name will equal "Pass this in"