I have been looking to make my application a little more scalable by specifying a base data model which I intend to act as a container so that the data sent through to another application is always of the correct structure.
However I want to be able to easily load data from sources such as XML and databases in the future, so I was wondering how to go about copying the values of one object to the base data model object, where the object im copying the values from may not be of the same structure (so I mainly just want to match up property names).
Here is what I tried:
public Dictionary<string, object> ObjectValues(object source)
{
if(source == null)
return null;
Dictionary<string, object> properties = new Dictionary<string, object>();
foreach (PropertyInfo propInfo in source.GetType().GetProperties())
{
try
{
object value = propInfo.GetValue(source, null);
properties.Add(propInfo.Name, value);
if (!value.GetType().IsPrimitive && !value.GetType().IsValueType)
{
Dictionary<string, object> internalProperties = ProxyValues(value);
if (internalProperties != null)
foreach (KeyValuePair<string, object> internalProp in internalProperties)
properties.Add(String.Format("{0}.{1}", propInfo.Name, internalProp.Key), internalProp.Value);
}
}
catch (TargetParameterCountException) { }
}
return properties;
}
Thanks,
Alex.
If I understand your question correctly, you probably want to look at something like AutoMapper
You set up configurations:
Which will create a mapping from TypeA to TypeB, where the property PropA will be copied to PropB. Then when you want to use the mapping:
Mapping configurations can even use custom resolvers, so if you want to do complex work when copying, you can.
There is also ValueInjecter, which some people prefer over AutoMap