这是我继承的代码而不是我的设计。
正在进行一项重大调查以恢复对象列表。然后使用查询结果创建自定义对象列表。有大量的循环存在以获得不同的值,例如县,州等。为了优化代码,我试图从查询结果中选择不同的值,并使用AddRange将它们添加到新集合中。但是,这会导致对每个值调用SQL。
INITIAL QUERY
using (var db = new StorageEntities())
{
db.Configuration.AutoDetectChangesEnabled = false;
List<CompanyTitleFeeSchedule> list = db.CompanyTitleFeeScheduleCompanies
.Include(x => x.Company)
.Include(x => x.CompanyTitleFeeSchedule)
.Include(x => x.CompanyTitleFeeSchedule.CompanyTitleFeeScheduleAreas)
.Include(x => x.CompanyTitleFeeSchedule.CompanyTitleFeeScheduleCompanies)
.Include(x => x.CompanyTitleFeeSchedule.CompanyTitleFeeScheduleAreas.Select(t => t.County))
.Include(x => x.CompanyTitleFeeSchedule.CompanyTitleFeeScheduleAreas.Select(t => t.County.State))
.Where(x => x.CompanyID == id || x.Company.ParentCompanyID == id)
.Select(x => x.CompanyTitleFeeSchedule).Distinct().ToList();
return list.Select(item => new VM.CompanyTitleFeeScheduleViewModel(item)).ToList();
}
**在构造函数VM.CompanyTitleFeeScheduleViewModel中,它包含CountyViewModel的List,我试图用查询结果中的不同县填充它。这导致对每个不同的县调用数据库。即使我需要的值已经在查询结果中。由于列表已经枚举,为什么实体需要返回数据库? **
//Get a list of distinct counties and add them to the collection
Counties.AddRange((from c in data.CompanyTitleFeeScheduleAreas
group c by c.CountyID
into cty
select cty.First())
.Select(cty => new CountyViewModel
{
CountyID = cty.CountyID,
Name = cty.County.Name,
StateID = cty.County.StateID
}));
答案 0 :(得分:1)
我在几年内没有使用EF,但最后我做了,你通常需要使用Include
来加载相关实体和查询。否则,相关实体会根据需要延迟加载。
像:
...
.Select(x => x.CompanyTitleFeeSchedule)
.Include(x => x.CompanyTitleFeeScheduleAreas) // added this.
...
有关详细信息,请参阅:Loading Related Entities
该帖子还告诉您如何在各种情况下禁用延迟加载。