2011-05-13 32 views
10

Dadas estas clases, ¿cómo puedo mapear un diccionario de ellas?Mapeo de diccionarios con AutoMapper

public class TestClass 
{ 
    public string Name { get; set; } 
} 

public class TestClassDto 
{ 
    public string Name { get; set; } 
} 


Mapper.CreateMap<TestClass, TestClassDto>(); 
Mapper.CreateMap<Dictionary<string, TestClass>, 
        Dictionary<string, TestClassDto>>(); 

var testDict = new Dictionary<string, TestClass>(); 
var testValue = new TestClass() {Name = "value1"}; 
testDict.Add("key1", testValue); 

var mappedValue = Mapper.Map<TestClass, TestClassDto>(testValue); 

var mappedDict = Mapper.Map<Dictionary<string, TestClass>, 
          Dictionary<string, TestClassDto>>(testDict); 

Mapeando uno de ellos, mappedValue en este caso, funciona bien.

Al mapear un diccionario de ellos termina sin entradas en el objeto de destino.

¿Qué estoy haciendo worng?

Respuesta

13

El problema que está teniendo es porque AutoMapper está luchando para asignar el contenido del Diccionario. Debe pensar de qué se trata: en este caso, KeyValuePairs.

Si intenta crear un asignador para la combinación KeyValuePair que va a trabajar rápidamente que no se puede directamente como la propiedad Key no tiene un colocador.

AutoMapper soluciona esto permitiéndole hacer un mapa utilizando el constructor.

/* Create the map for the base object - be explicit for good readability */ 
Mapper.CreateMap<TestClass, TestClassDto>() 
     .ForMember(x => x.Name, o => o.MapFrom(y => y.Name)); 

/* Create the map using construct using rather than ForMember */ 
Mapper.CreateMap<KeyValuePair<string, TestClass>, KeyValuePair<string, TestClassDto>>() 
     .ConstructUsing(x => new KeyValuePair<string, TestClassDto>(x.Key, 
                    x.Value.MapTo<TestClassDto>())); 

var testDict = new Dictionary<string, TestClass>(); 
var testValue = new TestClass() 
{ 
    Name = "value1" 
}; 
testDict.Add("key1", testValue); 

/* Mapped Dict will have your new KeyValuePair in there */ 
var mappedDict = Mapper.Map<Dictionary<string, TestClass>, 
Dictionary<string, TestClassDto>>(testDict); 
+0

Tenga en cuenta que el segundo bit ConstructUsing utiliza el primer mapa para hacer su trabajo. –