【发布时间】:2019-12-09 22:27:43
【问题描述】:
我有一个映射到 SQL 表的实体类:
public class EntityItem {
public virtual ICollection<EntityItem2> SomeItems { get; set; }
}
我有以下两个sn-ps:
var items = _repository.Table.Where(x => x.Id == id)
.Select(x => new ItemModel {
Items = x.SomeItems.Select(y => new SomeItem { //mapping is here...}).ToList()
});
和
var items = _repository.Table.Where(x => x.Id == id).Select(x => someModelMapper.BuildModel(x));
//inside a mapper
public ItemModel BuildModel(EntityType entity){
var model = new ItemModel();
model.Items = entity.SomeItems.Select(x => anotherMapper.BuildModel(x));
return model;
}
因此,我在这两种情况下都得到了不同的 SQL 查询。此外,第二个 sn-p 的工作速度比第一个慢得多。正如我在 SQL 探查器中看到的那样,第二个 snipper 正在生成许多 SQL 查询。 所以我的问题:
- 为什么会这样?
- 如何像在第二个 sn-p 中一样创建新对象,但要避免 大量 SQL 查询?
【问题讨论】:
标签: entity-framework linq linq-to-sql entity-framework-core