Extensions and Reflections and Generics oh my!

Copyright - https://www.flickr.com/photos/dcwriterdawn/

Creating an extension class for View Models to save public properties using Generics and Delegates, replacing a reflection implementation.

Introduction

Recently I was working on an MVC project in which the client wanted to persist a form used to filter data to a data store so that the form could be recalled with any number of saved states. I chose to persist the data in a dictionary object which could be persisted in a Entity Attribute Value table. 

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) =>
            {
                if (dict.Keys.Contains(nameof(deleg.name)))
                    deleg.name = dict[nameof(deleg.name)];
                if (dict.Keys.Contains(nameof(deleg.currentdate)))
                    deleg.currentdate = DateTime.Parse(dict[nameof(deleg.currentdate)]);
                if (dict.Keys.Contains(nameof(deleg.age)))
                    deleg.age = int.Parse(dict[nameof(deleg.age)]);

            }, pass_this_in);

            //ViewModel2015.name will equal "Pass this in"




Comments

Popular posts from this blog

Working with DocuSign

Getting the CycleGear Bilt Techno 2.0 with Sena DWO-5 headset to work with Sena's Driver software.

A new posting to CodeProject.