Search code examples
c#.netmodel-view-controller

Possible null reference return ( code 5.0 to 7.0)


I am working on 5.0 in which below function is working fine.

public async Task<Student> GetStudentAsync(Guid studentId)
{
    return await context.Student.Include(nameof(Gender)).Include(nameof(Address))
                .FirstOrDefaultAsync(x => x.Id == studentId); 
}

Here few more code unable to share all

 public async Task<bool> UpdateStudent(Guid Id, string ImageUrl)
        {
            var student = await GetStudentAsync(Id);

            if (student != null)
            {
                student.ImageUrl = ImageUrl;
                await context.SaveChangesAsync();
                return true;
            }
            return false;
        }

But while using the same code .net 7.0 unable to perform operation. Please suggest.


Solution

  • It seems that during migration you also have enabled nullable reference types. FirstOrDefaultAsync will return null if enumeration yields no results (hence there is no student with passed id). You can either disable NRTs or fix the method signature Task<Student> -> Task<Student?> (which makes more sense based on the following null check):

    public async Task<Student?> GetStudentAsync(Guid studentId)
    {
        // ...
    }
    

    And the warning/error in the title should go away.