如何映射一个匿名对象由AutoMapper一类? [英] how to map an anonymous object to a class by AutoMapper?

查看:2784
本文介绍了如何映射一个匿名对象由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; }
}

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

and I query the entity like this (by EF or NH):

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

现在,我怎么能映射 tagsAnon (作为一个的匿名对象的),以集合 TagModel (如的ICollection< TagModel> 的IEnumerable< TagModel> )?这可能吗?

Now, how can I map the tagsAnon (as an anonymous object) to a collection of TagModel (e.g. ICollection<TagModel> or IEnumerable<TagModel>)? Is it possible?

推荐答案

是的,这是可能的。你将不得不使用Automapper的Mapper类的DynamicMap方法对你有每个匿名对象。事情是这样的:

Yes, it is possible. You would have to use the DynamicMap method of the Automapper's Mapper class for each anonymous object you have. Something like this:

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

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






更新:< A HREF =htt​​ps://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API#unsupported-operations> DynamicMap现在已经过时。

现在,你需要从设置配置 CreateMissingTypeMaps 创建一个映射到真正

Now you need to create a mapper from a configuration that sets CreateMissingTypeMaps to 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();

这篇关于如何映射一个匿名对象由AutoMapper一类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆