我正在研究应用程序的缓慢性能(页面在Azure上加载8秒以上),并发现有趣的事情。
以下代码执行时间约为0.318秒
var reservations = db.Reservations.Include(r => r.PickUpLocation);
var reservationsList = reservations.ToList();
但是如果我手动加载导航属性,它将完成2.5倍(0.128秒)。
var reservations = db.Reservations.ToList();
var locations = db.Locations.ToList();
foreach (var r in reservations)
{
r.PickUpLocation = locations.FirstOrDefault(l => l.ID == r.PickUpLocationID);
}
对于更复杂的查询,差异甚至更高 - 最多20次(例如8秒与0.8秒)。
我尝试了QueryTrackingBehavior.NoTracking和QueryTrackingBehavior.TrackAll,对性能没有显着影响。
此外,我注意到实时Azure比本地计算机慢10倍,并且在EF /手动方法之间显示出更高的性能差异。
有没有办法让EF工作更快?
更新 位置表有121行(6个字符串列,1个布尔值和2个int) 预订表有1268行
预订模型类的重要部分:
public class Reservation
{
public int ID { get; set; }
...
[ForeignKey("PickUpLocation")]
public int PickUpLocationID { get; set; }
public Location PickUpLocation { get; set; }
...
}
位置模型类:
public class Location
{
public int ID { get; set; }
[StringLength(100)]
public string Name { get; set; }
[StringLength(255)]
public string Address { get; set; }
[StringLength(25)]
public string Barangay { get; set; }
[StringLength(25)]
public string City { get; set; }
[StringLength(25)]
public string Province { get; set; }
[StringLength(20)]
public string Country { get; set; }
[Display(Name = "Service Type")]
public LocationServiceType? ServiceType { get; set; }
[Display(Name = "Location Type")]
[Required]
public LocationType? LocationType { get; set; }
public bool IsDeleted { get; set; }
}
在执行详细登录的应用程序时,我可以看到实际执行的SQL查询。 EF7只做一个查询:
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [r].[ID], [r].[AssignedUnitID], [r].[AssignedUnitThirdParty], [r].[BookingCode], [r].[Comments], [r].[DailyPriceID], [r].[DamageDescription], [r].[DocumentCountry], [r].[DocumentNumber], [r].[DocumentOwnerName], [r].[DocumentType], [r].[Email], [r].[FirstName], [r].[FlightArrival], [r].[FlightNumber], [r].[HomeAddress], [r].[LastName], [r].[Phone], [r].[PickUpDateTime], [r].[PickUpLocationID], [r].[RequestedVehicleModelID], [r].[RequestedVehicleTypeID], [r].[ReturnDateTime], [r].[ReturnLocationID], [r].[State], [r].[StayingAddress], [r].[ThirdPartyName], [r].[Type], [r].[UserId], [r].[VersionDate], [l].[ID], [l].[Address], [l].[Barangay], [l].[City], [l].[Country], [l].[IsDeleted], [l].[LocationType], [l].[Name], [l].[Province], [l].[ServiceType]
FROM [Reservation] AS [r]
INNER JOIN [Location] AS [l] ON [r].[PickUpLocationID] = [l].[ID]
所以问题必须在于它如何解析结果。