2012-03-09 297 views
27

我有一个实体:如何通过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; } 
} 

和模型:

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; } 
} 

和我查询这样的实体(由EFNH):

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

现在,我该如何映射tagsAnon(作为ano nymous object)集合到TagModel(例如, ICollection<TagModel>IEnumerable<TagModel>)?可能吗?

+0

为什么不直接映射'Tag'到'TagModel'?为什么中间对象? – 2012-03-11 01:41:14

回答

2

我不完全确定这是否可能。建议:

为什么你就不能做到这一点:

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

这应该工作,但它失败(我已阅读,DynamicMap是集合玄乎

这证明。 DynamicMap可以和匿名类型一起工作,只是看起来不像枚举类型:

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

是的,这是可能的。您必须为每个匿名对象使用Automapper的Mapper类的DynamicMap方法。事情是这样的:

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

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

更新DynamicMap is now obsolete

现在,你需要从设置CreateMissingTypeMapstrue配置创建一个映射:

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

从AutoMapper 4.1开始不推荐使用,现在该怎么办? – MobileMon 2016-05-03 12:46:25

+3

@MobileMon我已经用新的方式更新了答案。感谢您指出。 – 2016-05-11 14:28:24

+1

我可以使用“CreateMissingTypeMaps = true”确认作品。这个答案应该被标记为有效。谢谢! – 2017-04-07 07:02:20

相关问题