在我的服务中,首先我生成了 40,000 个可能的母国和东道国组合,如下所示(clientLocations
包含 200 条记录,因此 200 x 200 是 40,000):
foreach (var homeLocation in clientLocations)
{
foreach (var hostLocation in clientLocations)
{
allLocationCombinations.Add(new AirShipmentRate
{
HomeCountryId = homeLocation.CountryId,
HomeCountry = homeLocation.CountryName,
HostCountryId = hostLocation.CountryId,
HostCountry = hostLocation.CountryName,
HomeLocationId = homeLocation.LocationId,
HomeLocation = homeLocation.LocationName,
HostLocationId = hostLocation.LocationId,
HostLocation = hostLocation.LocationName,
});
}
}
然后,我运行以下查询来查找上述位置的现有费率,但也包括清空缺失的费率;从而生成 40,000 行的完整记录集。
var allLocationRates = (from l in allLocationCombinations
join r in Db.PaymentRates_AirShipment
on new { home = l.HomeLocationId, host = l.HostLocationId }
equals new { home = r.HomeLocationId, host = (Guid?)r.HostLocationId }
into matches
from rate in matches.DefaultIfEmpty(new PaymentRates_AirShipment
{
Id = Guid.NewGuid()
})
select new AirShipmentRate
{
Id = rate.Id,
HomeCountry = l.HomeCountry,
HomeCountryId = l.HomeCountryId,
HomeLocation = l.HomeLocation,
HomeLocationId = l.HomeLocationId,
HostCountry = l.HostCountry,
HostCountryId = l.HostCountryId,
HostLocation = l.HostLocation,
HostLocationId = l.HostLocationId,
AssigneeAirShipmentPlusInsurance = rate.AssigneeAirShipmentPlusInsurance,
DependentAirShipmentPlusInsurance = rate.DependentAirShipmentPlusInsurance,
SmallContainerPlusInsurance = rate.SmallContainerPlusInsurance,
LargeContainerPlusInsurance = rate.LargeContainerPlusInsurance,
CurrencyId = rate.RateCurrencyId
});
我尝试使用.AsEnumerable()
和.AsNoTracking()
,这大大加快了速度。 以下代码将我的查询缩短了几秒钟:
var allLocationRates = (from l in allLocationCombinations.AsEnumerable()
join r in Db.PaymentRates_AirShipment.AsNoTracking()
但是,我想知道:我怎样才能进一步加快速度?
编辑:无法在 linq 中复制foreach
功能。
allLocationCombinations = (from homeLocation in clientLocations
from hostLocation in clientLocations
select new AirShipmentRate
{
HomeCountryId = homeLocation.CountryId,
HomeCountry = homeLocation.CountryName,
HostCountryId = hostLocation.CountryId,
HostCountry = hostLocation.CountryName,
HomeLocationId = homeLocation.LocationId,
HomeLocation = homeLocation.LocationName,
HostLocationId = hostLocation.LocationId,
HostLocation = hostLocation.LocationName
});
我在from hostLocation in clientLocations
上收到一个错误,上面写着"无法将IEnumerable类型转换为Generic.List"。
查询数据库的最快方法是使用数据库引擎本身的强大功能。
虽然 Linq 是一项出色的技术,但它仍然从 Linq 查询中生成一个 select 语句,并对数据库运行此查询。
最好的办法是创建数据库视图或存储过程。
视图和存储过程可以轻松地集成到 Linq 中。
材料视图(在MS SQL中)可以进一步加快执行速度,缺少索引是迄今为止加快数据库查询的最有效工具。
我怎样才能进一步加快速度?
优化是个婊子。
你的代码对我来说看起来不错。确保在适当的位置设置数据库架构上的索引。如前所述:针对 SQL 运行 Linq 以更好地了解性能。
好吧,但是无论如何如何提高性能呢?
您可能想看一眼以下链接:提高 LINQ to SQL 性能的 10 个技巧
对我来说,可能是列出的最重要的几点(在上面的链接中):
- 仅检索所需的记录数
- 关闭数据上下文的启用对象跟踪属性(如果不是)必要
- 使用 DataLoadOptions.AssociateWith 将数据筛选到您需要的内容。
- 在需要时使用已编译的查询(请注意该查询...