Skip to content

Instantly share code, notes, and snippets.

@chrismckelt
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismckelt/136311b42058c03b4a7a to your computer and use it in GitHub Desktop.
Save chrismckelt/136311b42058c03b4a7a to your computer and use it in GitHub Desktop.
var exp1 = @event.ToDto<CustomerCreatedEvent,CustomerDetail>( x=> x.AggregateId.As("CustomerId"), x => x.Email, x => x.FirstName, x => x.Surname);
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
return expando as ExpandoObject;
}
public static KeyValuePair<string, object> As(this object obj, string rename)
{
return new KeyValuePair<string, object>(rename, obj);
}
public static T2 ToDto<T1,T2>(this T1 obj, params Expression<Func<T1, dynamic>>[] items) where T1 : class
{
var eo = new ExpandoObject();
var props = eo as IDictionary<String, object>;
foreach (var thing in items)
{
var member = thing.Body as MemberExpression;
var unary = thing.Body as UnaryExpression;
var body = member ?? (unary != null ? unary.Operand as MemberExpression : null);
if (member != null && body.Member is PropertyInfo)
{
var property = body.Member as PropertyInfo;
if (property != null)
props[property.Name] = obj.GetType().GetProperty(property.Name).GetValue(obj, null);
}
else if (unary != null)
{
var ubody = (UnaryExpression)thing.Body;
var property = ubody.Operand as MemberExpression;
if (property != null)
{
props[property.Member.Name] = obj.GetType()
.GetProperty(property.Member.Name)
.GetValue(obj, null);
}
else // full expression with number funcs
{
var compiled = thing.Compile();
var result = (KeyValuePair<string, object>)compiled.Invoke(obj);
props[result.Key] = result.Value;
}
}
}
string json = JsonConvert.SerializeObject(eo); // need json.net
var anon = JsonConvert.DeserializeAnonymousType<object>(json, Activator.CreateInstance<T2>());
return ((JObject)anon).ToObject<T2>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment