Entity framework nested projections are slow

后端 未结 1 928
别那么骄傲
别那么骄傲 2020-12-12 02:05

I\'m running a query to fetch a users profile. The query get the users details, as well as all the reviews they have posted, as well as the comments in the reviews.

相关标签:
1条回答
  • 2020-12-12 02:24

    EF6's loading strategy of using one big SQL query per LINQ query is not optimal for loading complex object graphs. There are several other ways to get your graph loaded.

    For instance you could load the root AspNetUser entity, and then traverse the Navigation Properties to build your graph. EF would Lazy Load as needed. And once an entity is cached in the context, subsequent navigations would not cause additional queries.

    In fact if you pre-fetch some or all of the related entities, EF will "stitch" or "fix-up" your navigation properties.

    So as an optimization, you can write queries that fetch into the context cache the entities that you will need using a few simple and cheap queries.

    something like

     var user = context.AspNetUsers.Where(u => u.Id == userId).Single();
     var followers = context.Followers.Where(f => f.UserId == userId).ToList();
     var ratings = context.Ratings.Where(f => f.UserId == userId).ToList();
     var ratingIds = ratings.Select(r => r.Id).ToList();
     var ratingLikes = context.RatingLikes.Where(x => ratingIds.Contains(x.RatingId) && x.IsLiked ).ToList();
     var ratingPhotos = context.RatingPhotos.Where(x => ratingIds.Contains(x.RatingId)).ToList();
    

    Then build your results from the loaded AspNetUser, eg

      var u = user;
      var results =
                  select new UserVM
                        {
                             Name = u.UserName,
                             Id = u.Id,
                             ProfilePic = u.ProfilePicUrl,
                             FollowerCount = u.Followers.Count, . . .
    
    0 讨论(0)
提交回复
热议问题