Code
public class Test1
{
[Conversion("UserId")]
Public int id { get; set; }
[Conversion("UserValue")]
public int value { get; set; }
[Conversion("UserInfo")]
public List<Test2> info { get; set; }
}
public class User
{
public int UserId { get; set; }
public int UserValue { get; set; }
public List<UserInformation> UserInfo { get; set; }
}
public class Test2
{
[Conversion("UserId")]
public int id { get; set; }
[Conversion("UserName")]
public string name { get; set; }
[Conversion("UserLocation")]
public string location { get; set; }
}
public class UserInformation
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserLocation { get; set; }
}
public class ConversionAttribute
{
public string Name { get; set; }
public ConversionAttribute(string name)
{
this.Name = name;
}
}
public dynamic Convert(dynamic source, Type result)
{
var p = Activator.CreateInstance(result);
foreach (var item in source.GetType().GetProperties().Where(m => m.GetCustomAttributes(typeof(ConversionAttribute)).Count() > 0))
{
p.GetType().GetProperty(item.GetCustomAttributes(typeof(ConversionAttribute)).Cast<ConversionAttribute>().Name).Value = item.GetValue(source,null); // This should work for system types... but not for lists / custom models.
}
}
public void DoShit()
{
var t1 = new Test1 { id = 1, name = value = "Test", info = new Test2 { id = 1, name = "MyName", location = "UserLocation" } };
var obj = Convert(t1, typeof(User));
}
Situation
I've been tasked to transform our database model to our WCF model. They are different in several ways which I've shown a little bit in the example code above.
I've managed to create instances using Activator.CreateInstance(result)
and I can use source.GetType().GetProperties()
to copy all the properties, but I seem to have a problem when it comes to a Model (custom class) or a list.
Problem
I have no idea how to handle custom classes or lists (both of system type aswell as custom classes).
In my old method I used two methods, one for a normal conversion and one for a list conversion.. but my boss didn't approve it so I'd like to know if it is possible to have one method for every use without checking wether the type is a list, a custom class or a system type
The main reason this has to be fully generic and by use of attributes is because we plan to use this method in several projects aswell as over more then 100 models.