I thought to shar yet another of my experiences with Entity Framework 7 where Lazy Loading is still not implemented. I was actually designing my Movie-Review API and soon after that I realized that results are unexpected, hence without wasting time, I directly checked with Microsoft. Here is my conversation with Microsoft.
Therefore, below is the glimpse of the snippet, which was expected to work and the workaround which I have written to give the expected results.
  1. using Microsoft.AspNet.Mvc;
  2. using MovieReviewSPA.Data.Contracts;
  3. using MovieReviewSPA.Model;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using MovieReviewSPA.Web.ViewModels.Movie;
  8. using Microsoft.Data.Entity;
  9. namespace MovieReviewSPA.Web.Controllers.API
  10. {
  11. [Route("api/[controller]")]
  12. public class MoviesController : Controller
  13. {
  14. private IMovieReviewUow UOW;
  15. public MoviesController(IMovieReviewUow uow)
  16. {
  17. UOW = uow;
  18. }
  19. //TO DO:- Lazy loading is still not implemented in EF 7
  20. //Refer here https://github.com/aspnet/EntityFramework/issues/3312
  21. //Once, same get implemented, Below query will work without any issue
  22. // GET api/movies
  23. [HttpGet("")]
  24. public IQueryable Get()
  25. {
  26. /*var model = UOW.Movies.GetAll().OrderByDescending(m => m.Reviews.Count())
  27. .Select(m => new MovieViewModel
  28. {
  29. Id = m.Id,
  30. MovieName = m.MovieName,
  31. DirectorName = m.DirectorName,
  32. ReleaseYear = m.ReleaseYear,
  33. NoOfReviews = m.Reviews.Count()
  34. });*/
  35. //This is workaround for lazy loading
  36. var model = UOW.Movies.GetAll().Include(x => x.Reviews).OrderByDescending(m => m.Reviews.Count)
  37. .Select(m => new MovieViewModel
  38. {
  39. Id = m.Id,
  40. MovieName = m.MovieName,
  41. DirectorName = m.DirectorName,
  42. ReleaseYear = m.ReleaseYear,
  43. NoOfReviews = m.Reviews.Count
  44. });
  45. return model;
  46. }
  47. // Update an existing movie
  48. // PUT /api/movie/
  49. [HttpPut("")]
  50. public HttpResponseMessage Put([FromBody]Movie movie)
  51. {
  52. UOW.Movies.Update(movie);
  53. UOW.Commit();
  54. return new HttpResponseMessage(HttpStatusCode.NoContent);
  55. }
  56. // Create a new movie
  57. // POST /api/movies
  58. [HttpPost("")]
  59. public int Post([FromBody]Movie movie)
  60. {
  61. UOW.Movies.Add(movie);
  62. UOW.Commit();
  63. return Response.StatusCode = (int)HttpStatusCode.Created;
  64. }
  65. // DELETE api/movies/5
  66. [HttpDelete("{id}")]
  67. public HttpResponseMessage Delete(int id)
  68. {
  69. UOW.Movies.Delete(id);
  70. UOW.Commit();
  71. return new HttpResponseMessage(HttpStatusCode.NoContent);
  72. }
  73. }
  74. }
With this change in place, it produced the expected result as shown below.
Here, you can see that it stared giving me reviews count as well, without lazy loading it was giving 0 always.
Thanks,
Rahul Sahay
Happy Coding