The code was assuming that the ModuleDefinitionId exists in the PageState.Modules collection. Instead of using .Count() code now uses .FirstOrDefault() != null