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.
- using Microsoft.AspNet.Mvc;
- using MovieReviewSPA.Data.Contracts;
- using MovieReviewSPA.Model;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using MovieReviewSPA.Web.ViewModels.Movie;
- using Microsoft.Data.Entity;
-
- namespace MovieReviewSPA.Web.Controllers.API
- {
- [Route("api/[controller]")]
- public class MoviesController : Controller
- {
- private IMovieReviewUow UOW;
-
- public MoviesController(IMovieReviewUow uow)
- {
- UOW = uow;
- }
-
-
-
-
-
- [HttpGet("")]
- public IQueryable Get()
- {
-
-
-
-
-
-
-
-
-
-
-
- var model = UOW.Movies.GetAll().Include(x => x.Reviews).OrderByDescending(m => m.Reviews.Count)
- .Select(m => new MovieViewModel
- {
- Id = m.Id,
- MovieName = m.MovieName,
- DirectorName = m.DirectorName,
- ReleaseYear = m.ReleaseYear,
- NoOfReviews = m.Reviews.Count
- });
-
- return model;
- }
-
-
-
- [HttpPut("")]
- public HttpResponseMessage Put([FromBody]Movie movie)
- {
- UOW.Movies.Update(movie);
- UOW.Commit();
- return new HttpResponseMessage(HttpStatusCode.NoContent);
- }
-
-
-
- [HttpPost("")]
- public int Post([FromBody]Movie movie)
- {
- UOW.Movies.Add(movie);
- UOW.Commit();
- return Response.StatusCode = (int)HttpStatusCode.Created;
- }
-
-
-
- [HttpDelete("{id}")]
- public HttpResponseMessage Delete(int id)
- {
- UOW.Movies.Delete(id);
- UOW.Commit();
- return new HttpResponseMessage(HttpStatusCode.NoContent);
- }
-
- }
- }
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