如何通过AutoMapper将匿名对象映射到类?

age*_*t47 38 c# mapping anonymous-types 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; }
}
Run Code Online (Sandbox Code Playgroud)

和模型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我查询这样的实体(通过EFNH):

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

现在,我如何将tagsAnon(作为匿名对象)映射到TagModel(例如ICollection<TagModel>IEnumerable<TagModel>)的集合?可能吗?

Cai*_*ete 59

对的,这是可能的.您必须为您拥有的每个匿名对象使用Automapper的Mapper类的DynamicMap方法.像这样的东西:

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();
Run Code Online (Sandbox Code Playgroud)

更新:DynamicMap现已过时.

现在,您需要从设置CreateMissingTypeMaps为的配置创建映射器CreateMissingTypeMaps:

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

var tagsModel = tagsAnon.Select(Mapper.DynamicMap<TagModel>)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

  • @MobileMon我用新的方式更新了答案.谢谢你指出来. (4认同)

Jus*_*ony 4

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

为什么你不能这样做:

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

这应该有效,但是它失败了(我读到 DynamicMap 在集合上是不确定的。

var destination = Mapper.DynamicMap<IEnumerable<TagModel>>(tagsAnon);
Run Code Online (Sandbox Code Playgroud)

这证明 DynamicMap 确实适用于匿名类型,只是看起来不适用于枚举:

var destination = Mapper.DynamicMap<TagModel>(tagsAnon);
Run Code Online (Sandbox Code Playgroud)