我有使用EF 6.X的Web应用程序(ASP.NET MVC 5.X),我搜索和研究关于提高EF性能我使用这种方式来改进这一点。 我有一个查询,它有11个连接到另一个表,当我用EF Profiler配置此查询得到以下结果:
通知:
更多细节: 我的SQL查询行数 2260 ,TSQL查询为here。
如何改进此查询并获得最佳性能?
public Task<UserProfileDto> GetUserForProfileAsync(long accountId, Guid userId)
{
return _users
.AsNoTracking()
.Where(user => user.AccountId == accountId)
.Include(user => user.Certificates)
.Include(user => user.WorkExperiences)
.Include(user => user.ExchangeAccount)
.Include(user => user.SocialNetwork)
.Include(user => user.ActivityLogs)
.Include(user => user.Certificates)
.Include(user => user.Visitors)
.Include(user => user.Crafts)
.Include(user => user.Followings)
.Include(user => user.Followers)
.Include(user => user.Notifications)
.Select(user => new UserProfileDto()
{
NotificationCount = user.Notifications.Count(notification => !notification.IsRead),
FollowerCount = user.Followers.Count(following => following.FollowingId == user.Id),
FollowingCount = user.Followings.Count,
FollowedByCurrentUser = user.Followers.Any(following => following.FollowerId == userId),
PostCount = user.Posts.Count,
DisplayName = user.DisplayName,
AccountId = user.AccountId,
UserName = user.UserName,
ImageName = user.ImageName,
AvatarUrl = user.AvatarUrl,
LastSeen = user.LastSeen,
VisitorCount = user.Visitors.Count,
AboutMe = user.AboutMe,
IsAdmin = user.IsSystemAccount,
LastSeenMode = user.LastSeenMode,
IsSystemAccount = user.IsSystemAccount,
IsVerifiedAccount = user.IsVerifiedAccount,
WebSiteUrl = user.WebSiteUrl,
LastPosts =
user.Posts.Where(post => !post.IsDeleted)
.OrderByDescending(post => post.CreatedDate)
.Select(post => new UserLastPostDto()
{
Id = post.Id,
Title = post.Title,
CreatedDate = post.CreatedDate
})
.Take(5).ToList(),
LastActivityLogs =
user.ActivityLogs
.OrderByDescending(log => log.OperatedOn)
.Select(l => new UserLastActivity()
{
Description = l.Description
})
.Take(5).ToList(),
Certificates = user.Certificates,
Craft = user.Crafts,
ExchangeAccount = user.ExchangeAccount,
SocialNetwork = user.SocialNetwork.Select(network => new NetDto()
{
Icon = network.Icon,
UserName = network.UserName,
UserNameFormat = network.UserNameFormat
}).ToList(),
WorkExperiences = user.WorkExperiences,
})
.SingleOrDefaultAsync();
}