Reputation: 857
I am building a movie site. I am using mvc3 and entity framework. I am using mostly LINQ to Entities to query the database. the site GUI is basically one view page which beside the first loading, I use mainly Ajax to refresh the movie list according to the search criteria and such. So I use one main query. when I check this at debug mode i see that query takes 10 seconds every time to perform, which is of course very slow. I have indexed the database according to my basic knowledge. here is the main query code:
var casts = MovieCasts.Where(d =>
movieIds.Contains(d.MovieId)
&& d.WorkingTitleId != null &&
actorAndActressWtIds.Contains((int)d.WorkingTitleId)).AsEnumerable()
.Where(d=>GetMoviesTop4CelebIds(d.MovieId).Contains(d.CelebId))
.AsQueryable()
.Select(d =>new MCast
{
MovieId = d.MovieId,
Id = d.Id,
CelebId = d.CelebId,
CelebPageViews = d.Celebrity.PageViews,
ActingParts = string.Join(",",d.ActingParts.Select(e => e.Name)),
ActorName = HttpUtility.HtmlDecode(d.Celebrity.ShortName) ??
HttpUtility.HtmlDecode(d.Celebrity.BirthName),
}).ToList();
the GetMoviesTop4CelebIds() is a function that approaches the database directly and returns a short list of int (celebId) according to the movie Id. This is why I used the first AsEnumerable(), otherwise it gave error "LINQ to Entities does not recognize the method and cannot translate..." (a funny thing I should mention is that my code is slow in debug mode when I use break points and is fast without it. this is in development. In production the code is very slow.) can anyone please help me to shade some light on the code? I would really love and need to improve the performance.
Upvotes: 1
Views: 395
Reputation: 7135
Calling AsEnumerable()
will execute the Linq to Entities query at that point and cause the rest of the operation to be performed using Linq to Objects. Try executing GetMoviesTop4CelebIds()
separately before you execute this query and using the resultant values in the query instead of the method call.
Upvotes: 2