2012-03-09 17 views
27

Ho un'entità:come mappare un oggetto anonimo in una classe con AutoMapper?

public class Tag { 
    public int Id { get; set; } 
    public string Word { get; set; } 
    // other properties... 
    // and a collection of blogposts: 
    public ICollection<Post> Posts { get; set; } 
} 

e un modello:

public class TagModel { 
    public int Id { get; set; } 
    public string Word { get; set; } 
    // other properties... 
    // and a collection of blogposts: 
    public int PostsCount { get; set; } 
} 

e interrogo l'entità simili (da EF o NH):

var tagsAnon = _context.Tags 
    .Select(t => new { Tag = t, PostsCount = t. Posts.Count() }) 
    .ToList(); 

Ora, come posso mappare lo tagsAnon (come un ano nymous object) a una raccolta di TagModel (ad es. ICollection<TagModel> o IEnumerable<TagModel>)? È possibile?

+0

Perché non map 'Tag' direttamente a' TagModel'? Perché l'oggetto intermedio? –

risposta

2

Non sono del tutto sicuro che sia possibile. Suggerimenti:

perché non si può solo fare questo:

var tagsAnon = _context.Tags 
    .Select(t => new TagModel { Tag = t, PostsCount = t. Posts.Count() }) 
    .ToList(); 

questo dovrebbe funzionare, tuttavia non riesce (Ho letto che DynamicMap è incerto su collezioni

Ciò dimostra che. DynamicMap funziona con i tipi anon, solo non apparentemente con enumerabili:

var destination = Mapper.DynamicMap<TagModel>(tagsAnon); 
47

Sì, è possibile. Dovresti utilizzare il metodo DynamicMap della classe Mapper di Automapper per ogni oggetto anonimo che hai. Qualcosa di simile a questo:

var tagsAnon = Tags 
    .Select(t => new { t.Id, t.Word, PostsCount = t.Posts.Count() }) 
    .ToList(); 

var tagsModel = tagsAnon.Select(Mapper.DynamicMap<TagModel>) 
    .ToList(); 

Aggiornamento: DynamicMap is now obsolete.

Ora è necessario creare un mapper da una configurazione che imposta CreateMissingTypeMaps a true:

var tagsAnon = Tags 
    .Select(t => new { t.Id, t.Word, PostsCount = t.Posts.Count }) 
    .ToList(); 

var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true); 
var mapper = config.CreateMapper(); 

var tagsModel = tagsAnon.Select(mapper.Map<TagModel>) 
    .ToList(); 
+0

Questo è obsoleto come AutoMapper 4.1, cosa fare ora? – MobileMon

+3

@MobileMon Ho aggiornato la risposta con il nuovo modo di farlo. Grazie per segnalarlo. –

+1

Posso confermare l'utilizzo di "CreateMissingTypeMaps = true". Questa risposta dovrebbe essere contrassegnata come valida. Grazie! –

Problemi correlati