Ignorar la asignación de una propiedad con Automapper


Estoy usando Automapper y tengo el siguiente escenario: La clase OrderModel tiene una propiedad llamada 'ProductName' que no está en la base de datos. Así que cuando intento hacer el mapeo con:

Mapper.CreateMap<OrderModel, Orders>(); 

Genera una excepción :

" Las siguientes 1 propiedades en el Proyecto.ViewModels.OrderModel no están mapeados: 'ProductName'

He leído en Automapper's Wiki for Projections el caso opuesto (el atributo extra está en el destino, no en la fuente que es en realidad mi caso )

¿Cómo puedo evitar que automapper haga la asignación de esta propiedad?

Author: Andries Koorzen, 2011-02-14

8 answers

De Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

En uno de los comentarios en su blog.

 340
Author: smartcaveman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-27 12:28:53

Tal vez soy un poco perfeccionista; realmente no me gusta el ForMember(..., x => x.Ignore()) sintaxis. Es una cosita, pero me importa. Escribí este método de extensión para que sea un poco más agradable:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

Se puede usar así:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);

También podría reescribirlo para que funcione con params, pero no me gusta el aspecto de un método con un montón de lambdas.

 207
Author: Steve Rukuts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-29 08:23:56

Puedes hacer esto:

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.Ignore());
 69
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-16 19:12:42

Ahora hay (AutoMapper 2.0) un atributo IgnoreMap, que voy a usar en lugar de la sintaxis fluida que es un poco pesada en MI humilde opinión.

 25
Author: Guillaume,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-23 08:45:51

Solo para cualquiera que intente hacer esto automáticamente, puede usar ese método de extensión para ignorar las propiedades no existentes en el tipo de destino:

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

Se utilizará de la siguiente manera :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

Gracias a Can Gencer por la punta:)

Fuente : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

 24
Author: Stéphane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-13 15:30:19

Al asignar un modelo de vista a un modelo de dominio, puede ser mucho más limpio simplemente validar la lista de miembros de origen en lugar de la lista de miembros de destino

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

Ahora mi validación de asignación no falla, requiriendo otro Ignore(), cada vez que agrego una propiedad a mi clase de dominio.

 10
Author: Loren Paulsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-15 03:49:07

Me gustó una extensión añadida por Steve Rukuts, así que decidí agregar un método de extensión más basado en su ejemplo. Espero que ayude a alguien:

    public static IMappingExpression<TSource, TDestination> Map<TSource, TDestination>(
        this IMappingExpression<TSource, TDestination> map,
        Expression<Func<TSource, object>> src,
        Expression<Func<TDestination, object>> dst)
    {
        map.ForMember(dst, opt => opt.MapFrom(src));
        return map;
    }

Uso:

    Mapper.Initialize(cfg => cfg.CreateMap<UserModel, UserDto>()
        .Map(src => src.FirstName + " " + src.LastName, dst => dst.UserName));
 -2
Author: Alex Valchuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-08 09:12:51

Hola A todos Por favor Utilice esto está funcionando bien... para el mapeador automático use múltiples .En diciembre{[3] } en C #

        if (promotionCode.Any())
        {
            Mapper.Reset();
            Mapper.CreateMap<PromotionCode, PromotionCodeEntity>().ForMember(d => d.serverTime, o => o.MapFrom(s => s.promotionCodeId == null ? "date" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", DateTime.UtcNow.AddHours(7.0))))
                .ForMember(d => d.day, p => p.MapFrom(s => s.code != "" ? LeftTime(Convert.ToInt32(s.quantity), Convert.ToString(s.expiryDate), Convert.ToString(DateTime.UtcNow.AddHours(7.0))) : "Day"))
                .ForMember(d => d.subCategoryname, o => o.MapFrom(s => s.subCategoryId == 0 ? "" : Convert.ToString(subCategory.Where(z => z.subCategoryId.Equals(s.subCategoryId)).FirstOrDefault().subCategoryName)))
                .ForMember(d => d.optionalCategoryName, o => o.MapFrom(s => s.optCategoryId == 0 ? "" : Convert.ToString(optionalCategory.Where(z => z.optCategoryId.Equals(s.optCategoryId)).FirstOrDefault().optCategoryName)))
                .ForMember(d => d.logoImg, o => o.MapFrom(s => s.vendorId == 0 ? "" : Convert.ToString(vendorImg.Where(z => z.vendorId.Equals(s.vendorId)).FirstOrDefault().logoImg)))
                .ForMember(d => d.expiryDate, o => o.MapFrom(s => s.expiryDate == null ? "" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", s.expiryDate))); 
            var userPromotionModel = Mapper.Map<List<PromotionCode>, List<PromotionCodeEntity>>(promotionCode);
            return userPromotionModel;
        }
        return null;
 -3
Author: ravikant sonare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 14:04:38