private async void DoWork(object state) { using (var scope = _scopeFactory.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService <LunchVoteContext>(); var voteRepository = new VoteRepository(dbContext); var todaysElection = await voteRepository.GetTodaysElectionAsync(); if (todaysElection != null && todaysElection.WinnerRestaurantId == Guid.Empty) { var winnerRestaurant = todaysElection.Votes .GroupBy(v => v.RestaurantId).Select(r => new { Value = r.Key, Count = r.Count() }) .OrderByDescending(o => o.Count); if (winnerRestaurant.FirstOrDefault() != null) { voteRepository.FinishElection(todaysElection.Id, winnerRestaurant.FirstOrDefault().Value); } } } }