C# 从列表中使用AddRange会导致多个数据库跳闸
这是我继承的代码,不是我的设计 正在进行一个大查询以返回对象列表。然后使用查询结果创建自定义对象的列表。存在大量循环,以获取不同的值,例如县、州等。。为了优化代码,我尝试从查询结果中选择不同的值,并使用AddRange将它们添加到新集合中。但是,这会导致对每个值调用SQL 初始查询C# 从列表中使用AddRange会导致多个数据库跳闸,c#,.net,linq,entity-framework,entity-framework-6,C#,.net,Linq,Entity Framework,Entity Framework 6,这是我继承的代码,不是我的设计 正在进行一个大查询以返回对象列表。然后使用查询结果创建自定义对象的列表。存在大量循环,以获取不同的值,例如县、州等。。为了优化代码,我尝试从查询结果中选择不同的值,并使用AddRange将它们添加到新集合中。但是,这会导致对每个值调用SQL 初始查询 using (var db = new StorageEntities()) { db.Configuration.AutoDetectChangesEnabl
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();
}
我已经有几年没有使用EF了,但最近我使用了,您通常需要使用
Include
来加载相关实体和查询。否则,相关实体会根据需要延迟加载
比如:
有关详细信息,请参阅:
这篇文章还告诉您如何在各种场景中禁用延迟加载
//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
}));
...
.Select(x => x.CompanyTitleFeeSchedule)
.Include(x => x.CompanyTitleFeeScheduleAreas) // added this.
...