I've started to use https://github.com/robconery/massive for a project, I wonder if there is any mapping tool that allows support for Dynamic to static type mapping?
I've used AutoMapper previously, does AutoMapper support this?
I am aware of the DynamicMap function from AutoMapper, however I believe this function is for running maps without creating the Map first. In my example below it does not work.
dynamic curUser = users.GetSingleUser(UserID); var retUser = Mapper.DynamicMap<UserModel>(curUser); users.GetSingleUser(UserID); // returns a dynamic object
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.
AutoMapper is an object-object mapper that allows you to solve the problem of manually mapping each property of a class with the same properties of another class. Before AutoMapper was introduced if we wanted to assign one object property to another object property then we were following a long procedure.
AutoMapper 4.2.0 now supports Dynamic/expando/dictionary mapping
With this feature you can map to your expando objects to static types:
dynamic CurUser = _users.GetSingleUser(UserID); var config = new MapperConfiguration(cfg => { }); var mapper = config.CreateMapper(); var retUser = mapper.Map<UserModel>(CurUser);
Old versions of AutoMapper do not support this (Massive internally uses ExpandoObject
which doesn't provide which properties it has), and you are right Mapper.DynamicMap
is for mapping without creating mapping configuration.
Actually it's not hard to write yourself a mapper if you just want simple mapping:
public static class DynamicToStatic { public static T ToStatic<T>(object expando) { var entity = Activator.CreateInstance<T>(); //ExpandoObject implements dictionary var properties = expando as IDictionary<string, object>; if (properties == null) return entity; foreach (var entry in properties) { var propertyInfo = entity.GetType().GetProperty(entry.Key); if(propertyInfo!=null) propertyInfo.SetValue(entity, entry.Value, null); } return entity; } } dynamic CurUser = _users.GetSingleUser(UserID); var retUser = DynamicToStatic.ToStatic<UserModel>(CurUser);
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