Home > Software engineering >  ASP.NET Core Web API - How to resolve Error CS0103 The name 'score' does not exist in the
ASP.NET Core Web API - How to resolve Error CS0103 The name 'score' does not exist in the

Time:09-11

In ASP.NET Core 6, I have this code.

public static class Paginator
{
    public static async Task<PageResult<IEnumerable<TDestination>>> PaginationAsync<TSource, TDestination>(this IQueryable<TSource> querable, int pageSize, int pageNumber, IMapper mapper)
        where TSource : class
        where TDestination : class
    {
        var count = querable.Count();
        var pageResult = new PageResult<IEnumerable<TDestination>>
        {
            PageSize = (pageSize > 10 || pageSize < 1) ? 10 : pageSize,
            CurrentPage = pageNumber > 1 ? pageNumber : 1,
            TotalRecord = count,
            PreviousPage = pageNumber > 0 ? pageNumber - 1 : 0
        };
        pageResult.NumberOfPages = count % pageResult.PageSize != 0
                ? count / pageResult.PageSize   1
                : count / pageResult.PageSize;
        var sourceList = await querable.Skip((pageResult.CurrentPage - 1) * pageResult.PageSize).Take(pageResult.PageSize).ToListAsync();
        var destinationList = mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(sourceList);
        pageResult.PageItems = destinationList;
        return pageResult;
    }
}

Repository interface:

IQueryable<Score> GetExamScoreAsync(PagingFilter filter)

Repository implementation:

public IQueryable<Score> GetExamScoreAsync(PagingFilter filter)
{
    var examScores = _dbContext.Scores
            .Where(m => (bool)m.Approval.IsFirstLevel == false)
            .Where(x => string.IsNullOrEmpty(filter.SearchQuery)
        || x.Subject.ToLower().Contains(filter.SearchQuery.ToLower())
        || x.StartDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Contains(filter.SearchQuery.ToLower())
        || x.EndDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Contains(filter.SearchQuery.ToLower()))
            .OrderByDescending(x => x.CreatedAt);
    return examScores;
}

Then I called it it the service:

public async Task<Response<PageResult<IEnumerable<ScoreListDto>>>> GetScoreAsync(PagingFilter filter)
{
    var userName = _currentUserService.UserName;
    var getUser = await _userManager.FindByNameAsync(userName);
    var loggedUserRole = await _userManager.GetRolesAsync(getUser);
    var loggedUserRoleName = loggedUserRole[0].ToString();

    if (loggedUserRoleName == "Student")
    {
        var score = await _unitOfWork.ExamScore.GetExamScoreStudentAsync(filter);
    }
    else
    {
        var score = await _unitOfWork.ExamScore.GetExamScoreAsync(filter);
    }
        
    var item = await score.PaginationAsync<Score, ScoreListDto>(filter.PageSize, filter.PageNumber, _mapper);

    return new Response<PageResult<IEnumerable<ScoreListDto>>>()
    {
        StatusCode = (int)HttpStatusCode.OK,
        Successful = true,
        Data = item
    };
}

I got this error:

Error CS0103 The name 'score' does not exist in the current context

Score is highlighted in:

var item = await score.PaginationAsync<Score, ScoreListDto>(filter.PageSize, filter.PageNumber, _mapper);

How do I resolve this?

Thanks

CodePudding user response:

Each block where you define var score (between the if {} and the else{}) determines the scope of the variable. In Javascript, which you might be more used to, the scope of a var is "hoisted" to the top-level of a function. This is not so in C#. You have to declare the variable within the scope where you're going to use it. So, you'll have to define it before the if statement so that it's available at the point where you call score.PaginationAsync call. Something like this:

    MyScoreType score;
    if (loggedUserRoleName == "Student")
    {
        score = await _unitOfWork.ExamScore.GetExamScoreStudentAsync(filter);
    }
    else
    {
        score = await _unitOfWork.ExamScore.GetExamScoreAsync(filter);
    }

An alternative approach would be to inline the if statement like this:

var score = (loggedUserRoleName == "Student")
    ? await _unitOfWork.ExamScore.GetExamScoreStudentAsync(filter)
    : (loggedUserRoleName == "Teacher")
        ? await _unitOfWork.ExamScore.GetExamScoreTeacherAsync(filter)
        : await _unitOfWork.ExamScore.GetExamScoreAsync(filter);

CodePudding user response:

You're declaring the 'score' variable within the if-else statement, so it's scope only remains in the if-else statement. Just declare it before the if statement and it should be accessible.

var score = new Score(); //Assuming Score is the data type your varaiable has
if (loggedUserRoleName == "Student")
{
    score = await _unitOfWork.ExamScore.GetExamScoreStudentAsync(filter);
}
else
{
    score = await _unitOfWork.ExamScore.GetExamScoreAsync(filter);
}
  • Related