我有一个实体:
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();