所有我有以下两种方法,并且希望将两者结合起来,一种方法不需要任何联接,而另一种方法则需要那些如何将这两种方法结合起来的方法
internal static IQueryable<ConstructionSet> CalculateSelectedConstructionSetsForOSM(Guid? ashraeClimateZoneId,
Guid? energyCodeId,
Guid? massingTypeId,
APIDbContext dbContext)
{
if (dbContext is null)
{
throw new ArgumentNullException(nameof(dbContext));
}
return dbContext.ConstructionSets.Include(p => p.AshraeClimateZone)
.Include(p => p.MassingType)
.Include(p => p.SourceOfData)
.Include(p => p.ExteriorWall)
.Include(p => p.ExteriorFloor)
.Include(p => p.InteriorFloor)
.Include(p => p.InteriorWall)
.Include(p => p.SlabOnGrade)
.Include(p => p.BelowGradeWall)
.Include(p => p.Glazing)
.Include(p => p.Roof)
.Where(p => p.AshraeClimateZoneId == ashraeClimateZoneId
&& p.SourceOfDataId == energyCodeId
&& p.MassingTypeId == massingTypeId
&& p.Revision != null
&& p.IsApproved == true)
.AsEnumerable()
.OrderByDescending(i => i.Revision)
.GroupBy(i => i.InitialRevisionId)
.Select(g => g.First()).AsQueryable();
}
以下是另一种方法
internal static IQueryable<ConstructionSet> CalculateSelectedConstructionSetsForProject(Guid? ashraeClimateZoneId,
Guid? energyCodeId,
Guid? massingTypeId,
APIDbContext dbContext)
{
if (dbContext is null)
{
throw new ArgumentNullException(nameof(dbContext));
}
return dbContext.ConstructionSets.Include(p => p.AshraeClimateZone)
.Include(p => p.MassingType)
.Include(p => p.SourceOfData)
.Where(p => p.AshraeClimateZoneId == ashraeClimateZoneId
&& p.SourceOfDataId == energyCodeId
&& p.MassingTypeId == massingTypeId
&& p.Revision != null
&& p.IsApproved == true)
.AsEnumerable()
.OrderByDescending(i => i.Revision)
.GroupBy(i => i.InitialRevisionId)
.Select(g => g.First()).AsQueryable();
}
任何人都可以让我知道如何结合使用这些方法。在此先感谢您。
答案 0 :(得分:3)
假设“组合它们”是指“重构它们,以便一个方法可以处理两种情况”,您可以执行以下操作:
internal static IQueryable<ConstructionSet> CalculateSelectedConstructionSets(Guid? ashraeClimateZoneId,
Guid? energyCodeId,
Guid? massingTypeId,
APIDbContext dbContext,
bool includeOsmNavigationProperties)
{
if (dbContext is null)
{
throw new ArgumentNullException(nameof(dbContext));
}
var sets = dbContext.ConstructionSets.Include(p => p.AshraeClimateZone)
.Include(p => p.MassingType)
.Include(p => p.SourceOfData);
if(includeOsmNavigationProperties)
{
sets = sets.Include(p => p.ExteriorWall)
.Include(p => p.ExteriorFloor)
.Include(p => p.InteriorFloor)
.Include(p => p.InteriorWall)
.Include(p => p.SlabOnGrade)
.Include(p => p.BelowGradeWall)
.Include(p => p.Glazing)
.Include(p => p.Roof);
}
return sets.Where(p => p.AshraeClimateZoneId == ashraeClimateZoneId
&& p.SourceOfDataId == energyCodeId
&& p.MassingTypeId == massingTypeId
&& p.Revision != null
&& p.IsApproved == true)
.AsEnumerable()
.OrderByDescending(i => i.Revision)
.GroupBy(i => i.InitialRevisionId)
.Select(g => g.First()).AsQueryable();
}
作为旁注,您应该避免将其转换为.AsEnumerable()
然后再转换回.AsQueryable()
的模式。将结果设为IQueryable
会使返回的集合上的后续操作变慢(表达式需要在运行时进行编译),并且隐藏了您不会在数据库层执行后续操作的事实。有人可能会添加一个Where()
子句,却没有意识到他们仍然导致整个数据集都从数据库中加载出来。