Right to the point: How would I map a Dictionary<String, String> to a ViewModel? The ViewModel contains properties of the same name of the Dictionary keys.
To give more information, the program reads a database record and returns all of the values for the record in a Dictionary<String, String>. I only want to display 20-30 of these fields to the user while other processing happens behind the scenes with the other fields. I’ve made a ViewModel and strongly typed the view. I can manually assign the properties from the Dictionary<String, String> to the ViewModel properties, however this seems like the wrong way to fill the ViewModel.
I then tried using reflection to populate the fields, but again this seems like the wrong way to go about this.
foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
{
if (propertyInfo.PropertyType.Name.Equals("String"))
{
if (myClass.FieldValues.Keys.Contains(propertyInfo.Name))
{
propertyInfo.SetValue(this, myClass.FieldValues[propertyInfo.Name], null);
}
}
}
So again, is there a way I can populate my ViewModel using a Dictionary<String, String> where the Key values are the same name as the ViewModel property values?
If I were I’d be looking at setting up an ORM layer (Entity, Linq-to-Sql) to return strongly typed objects. This provides you with a much more type safe overall solution.
If you are stuck with
Dictionary<string,string>then you have three options:Reflection – you’ve already done that, that’s pretty straight forward.
Expressions/Reflection. You can compile an expression that does the conversion into a lambda once and simply call it as a method afterwards. This has the benefit of being faster at runtime than reflection. However, unless you are doing thousands of these operations per second, performance gained is not worth the extra effort.
dynamic/ExpandoObject. This somewhat experimental and would involve a strongly typed wrapper around a dynamic object.Heck, you can even not bother with
dynamicand have the property go to the dictionary dicrectly: