Created
June 19, 2013 21:44
-
-
Save krcourville/5818395 to your computer and use it in GitHub Desktop.
Demonstration of using generic structures to better organize mappings and the copying of data from a keyed datasource to an object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// datasource | |
private static Dictionary<string,object> sourceData = new Dictionary<string,object>{ | |
{"test1", "Joe"}, | |
{"test2", DateTime.Now}, | |
{"test3", 5} | |
}; | |
// | |
// target object | |
class Foo | |
{ | |
public string Name { get; set; } | |
public DateTime Dob { get; set; } | |
public int Age { get; set; } | |
} | |
// | |
// the mappings for Foo | |
private static Mappings<Foo> fooMaps = Mappings<Foo>.Create() | |
.Add("test1", i=>i.Name) | |
.Add("test2", i=>i.Dob) | |
.Add("test3", i=>i.Age) | |
; | |
// | |
// testing it | |
void Main() | |
{ | |
var target = new Foo(); | |
CopyStuff(fooMaps, s=>sourceData[s] ,target); | |
Console.WriteLine (target.Age); | |
Console.WriteLine (target.Dob); | |
Console.WriteLine (target.Name); | |
} | |
// | |
// used to copy from source to target | |
private static object CopyStuff<T>( Mappings<T> mappings, Func<string,object> source, object target){ | |
foreach (var map in mappings) | |
{ | |
var prop = GetProperty(map.PropertySelector); | |
prop.SetValue(target, source(map.Key)); | |
} | |
return target; | |
} | |
// | |
// helper to retrieve PropertyInfo | |
// from an expression | |
private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> property) { | |
PropertyInfo propertyInfo = null; | |
if (property.Body is MemberExpression) { | |
propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo; | |
} else { | |
propertyInfo = | |
(((UnaryExpression)property.Body).Operand as MemberExpression) | |
.Member as PropertyInfo; | |
} | |
return propertyInfo; | |
} | |
// | |
// A property mapping for a keyed | |
// datasource | |
public class Mapping<T> | |
{ | |
public string Key { get; set; } | |
public Expression<Func<T,object>> PropertySelector { get; set; } | |
} | |
// | |
// collection of mappings | |
public class Mappings<T>:List<Mapping<T>> | |
{ | |
public static Mappings<T> Create(){ | |
return new Mappings<T>(); | |
} | |
public Mappings<T> Add( string name, Expression<Func<T,object>> prop){ | |
this.Add(new Mapping<T>{ | |
Key = name, | |
PropertySelector = prop | |
}); | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment