允许使用AutoMapper或类似的dynamictypes的映射?
我已经开始使用https://github.com/robconery/massive作为一个项目,我想知道是否有任何映射工具允许dynamic支持静态types映射?
以前我用过AutoMapper,AutoMapper支持这个吗?
我知道AutoMapper的DynamicMap函数,但是我相信这个函数是用来在不创buildMap的情况下运行地图的。 在我下面的例子中,它不起作用。
dynamic curUser = users.GetSingleUser(UserID); var retUser = Mapper.DynamicMap<UserModel>(curUser); users.GetSingleUser(UserID); // returns a dynamic object
AutoMapper 4.2.0现在支持dynamic/扩展/字典映射
使用此function,您可以将您的expando对象映射到静态types:
dynamic CurUser = _users.GetSingleUser(UserID); var config = new MapperConfiguration(cfg => { }); var mapper = config.CreateMapper(); var retUser = mapper.Map<UserModel>(CurUser);
AutoMapper的旧版本不支持(Massive内部使用ExpandoObject
,它不提供它拥有的属性),而且你正确的Mapper.DynamicMap
是用于映射而不创build映射configuration的。
其实,如果你只是想简单的映射,你自己写一个映射器就不难了:
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);
试试Slapper.AutoMapper https://github.com/randyburden/Slapper.AutoMapper
Slapper.AutoMapper将dynamic数据映射到静态types
它适用于dynamic
和Dictionary<A, B>
这是真棒。
下面是一个示例(取自上面的URL),显示了它与Dictionary的工作方式:
public class Person { public int Id; public string FirstName; public string LastName; } [Test] public void CanMapMatchingFieldNamesWithEase() { // Arrange var dictionary = new Dictionary<string, object> { { "Id", 1 }, { "FirstName", "Clark" }, { "LastName", "Kent" } }; // Act var person = Slapper.AutoMapper.Map<Person>( dictionary ); // Assert Assert.NotNull( person ); Assert.That( person.Id == 1 ); Assert.That( person.FirstName == "Clark" ); Assert.That( person.LastName == "Kent" ); }
假设您使用框架返回ExpandoObject
您可以使用AutoMapper实现某种dynamic映射:
Mapper.CreateMap<ExpandoObject, UserModel>() .ForAllMembers((options) => options.ResolveUsing((resolution) => { var dictionary = (IDictionary<string, object>) resolution.Context.SourceValue; return dictionary[resolution.Context.MemberName]; })); ... dynamic CurUser = _users.GetSingleUser(UserID); var retUser = Mapper.Map<UserModel>(CurUser);
您可以使用ConstructUsing
方法创build任何types的复杂映射。