【问题标题】:Automapper unflatten by prefixAutomapper 按前缀展开
【发布时间】:2017-03-03 00:56:38
【问题描述】:

我有一个这样的例子:

class Fields
{
    string ContactOneName{get;set;}
    string ContactOnePhone{get;set;}
    string ContactOneSpouseName{get;set;}
    string ContactOneSpousePhone{get;set;}
}

我想映射到这样的模型:

class Contacts
{
    Contact ContactOne {get;set;}
    Contact ContactOneSpouse {get;set;}
}

class Contact
{
   string Name {get;set;}
   string Phone {get;set;}
}

有很多字段,我不想为每个字段编写映射。 这可能吗? 如果有怎么办?

注意:这个问题几乎与 AutoMapper unflattening complex objects of same type 重复,但我想要一个解决方案,而不是手动映射所有内容,因为在这种情况下,不值得使用 automapper。

【问题讨论】:

    标签: automapper


    【解决方案1】:

    你可以把this加:

    public static IMappingExpression<TSource, TDestination> ForAllMembers<TSource, TDestination, TMember>(
        this IMappingExpression<TSource, TDestination> mapping,
        Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> opt)
    {
        var memberType = typeof(TMember);
        var destinationType = typeof(TDestination);
    
        foreach(var prop in destinationType.GetProperties().Where(prop => prop.PropertyType.Equals(memberType)))
        {
            var parameter = Expression.Parameter(destinationType);
            var destinationMember = Expression.Lambda<Func<TDestination, TMember>>(Expression.Property(parameter, prop), parameter);
    
            mapping.ForMember(destinationMember, opt);
        }
    
        return mapping;
    }
    

    然后你可以配置如下映射:

    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Fields, Contacts>().ForAllMembers<Fields, Contacts, Contact>(x => { x.Unflatten(); });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多