【发布时间】:2012-03-27 05:20:08
【问题描述】:
我有一个实体:
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>)?有可能吗?
【问题讨论】:
-
为什么不将
Tag直接映射到TagModel?为什么是中间对象? -
@AndrewWhitaker 因为 Entity Framework 只理解
Select中的匿名类型,并且可以从中优化 SQL 查询。
标签: c# mapping automapper anonymous-types