我有一个实体:

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 ):
var tagsAnon = _context.Tags
    .Select(t => new { Tag = t, PostsCount = t. Posts.Count() })
    .ToList();

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

最佳答案

更新2019-07-31 : CreateMissingTypeMaps is now deprecated in AutoMapper v8, and will be removed in v9



更新2016-05-11 :DynamicMap is now obsolete

现在,您需要从将CreateMissingTypeMaps设置为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的DynamicMap<T>类的Mapper方法。像这样:
var tagsAnon = Tags
    .Select(t => new { t.Id, t.Word, PostsCount = t.Posts.Count() })
    .ToList();

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

09-27 23:47