private MovieListViewModel CreateMovieListViewModel(MovieFilterViewModel mi) { var vm = new MovieListViewModel(); vm.MovieFilter = mi ?? new MovieFilterViewModel(); vm.CurrentUser = TryGetCurrentUser; vm.WhoHasSeenMovie = GetWhoHasSeenList(); //Sort stuff if (string.IsNullOrEmpty(mi.SortBy)) mi.SortBy = "addedat"; var sli = SortSelectListItems.FirstOrDefault(el => el.Value == mi.SortBy); if (sli != null) sli.Selected = true; vm.SortByList = SortSelectListItems; //... vm.GenreList = GetGenreList(mi.Genre.HasValue ? mi.Genre.Value : -1); vm.PersonList = GetPersonList(mi.Person.HasValue ? mi.Person.Value : -1); vm.Users = _movieSystemService.DbEntities.Users.ToList().Select(el => (UserViewModel)el).ToList(); return vm; }
public ActionResult Index(MovieFilterViewModel mi) { var db = _movieSystemService.DbEntities; //db.ObjectStateManager. var vm = CreateMovieListViewModel(mi); var movies = MoviesWithReferences; ((ObjectQuery<Movie>)movies).MergeOption = MergeOption.NoTracking; movies = movies.Where(m => m.MovieAtStorages.Any(mas => !mas.Ignore)); if (!string.IsNullOrEmpty(mi.Search)) movies = movies.Where(e => e.Title.Contains(mi.Search) || e.MovieAtStorages.Any(mas=>mas.CleanedName.Contains(mi.Search))); if (mi.Person.HasValue) movies = movies.Where(m => m.Casts.Any(c => c.PersonId == mi.Person.Value)); if (mi.Genre.HasValue) movies = movies.Where(e => e.Genres.Any(d => d.Id == mi.Genre.Value)); switch (mi.SortBy.ToLowerInvariant()) { case "score": movies = movies.OrderByDescending(el => el.Score).ThenBy(el=>el.Title); break; case "year": movies = movies.OrderByDescending(el => el.Year).ThenBy(el => el.Title); break; case "runtime": movies = movies.OrderBy(el => el.Runtime).ThenBy(el => el.Title); break; case "title": movies = movies.OrderBy(el => el.Title); break; case "addedat": default: movies = movies.OrderByDescending(el => el.AddedAt).ThenBy(el => el.Title); break; } var sw = Stopwatch.StartNew(); List<Movie> movieList = movies.ToList(); ViewBag.DbCallTime = sw.ElapsedMilliseconds; if (mi.SelectedUsers != null && mi.SelectedUsers.Length > 0) { if (mi.SeenNotSeen == SeenNotSeen.NotSeen) { var idFilter = new HashSet<int>(from user in db.Users from ss in user.SeenStatuses where mi.SelectedUsers.Contains(user.Username) select ss.Movie.Id); movieList = movieList.Where(m => !idFilter.Contains(m.Id)).ToList(); } else { int selUsersCount = mi.SelectedUsers.Length; var idFilter = (from ug in from user in db.Users from ss in user.SeenStatuses where mi.SelectedUsers.Contains(user.Username) select new { MovieId = ss.Movie.Id, Username = user.Username } group ug by ug.MovieId into grp where grp.Count() == selUsersCount select grp.Key).ToList(); movieList = movieList.Where(m => idFilter.Contains(m.Id)).ToList(); } } vm.Movies = movieList; var totalPlayTime = vm.Movies.Sum(el => el.Runtime); vm.TotalPlayTime = totalPlayTime.HasValue ? totalPlayTime.Value : 0; return View(vm); }