I have an class called Contact and another class called ContactKeys that contain Int32 constants. Each constant maps to a property of the Contact class and has an identical name.
public class Contact
{
public string Name { get; set; }
public int Age { get; set; }
}
public static class ContactKeys
{
public const int Name = 5284;
public const int Age = 9637;
}
Using Automapper, I need to create a Dictionary<int, object> object where the key is a constant from ContactKey, and the value is provided by the property of the same name from the Contact class.
From this post I can see that could potentially serialize the Contact class to JSON and then map it. But I don't know how to then get the constants mapped.
Any ideas?
I don't know AutoMapper and why you need to use it to solve this problem but here is a solution using reflection:
Contact myContact = ...;
typeof(ContactKeys)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.ToDictionary(f => (int)f.GetValue(null),
f => typeof(Contact).GetProperty(f.Name).GetValue(myContact));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With