Nullability of reference types in value doesn’t match target type

Viewed 4373

I'm having a play will nullable reference types and Entity Framework Core. The method should asynchronously return a nullable User, but the compiler complains

CS8619
Nullability of reference types in value doesn’t match target type.

The source code is as follows

public class UserRepository : IUserRepository
{
    private readonly ApplicationDbContext DbContext;

    public UserRepository(ApplicationDbContext dbContext)
    {
        DbContext = dbContext;
    }

    public Task<User?> GetByEmailAddress(string emailAddress) =>
        DbContext.Users.SingleOrDefaultAsync(x => x.EmailAddress == emailAddress);
}

What is the correct way to write this code?

Update, I expect that having nullable turned on changes the meaning of SingleOrDefaultAsync to make it effectively mean Task<{Non null user}> so if I make my method async (like the following code) then the C# compiler will unwrap the User out of the Task<> and cast it as User?

    public async Task<User?> GetByEmailAddress(string emailAddress) =>
        await DbContext.Users.SingleOrDefaultAsync(x => x.EmailAddress == emailAddress);

Is there another way of doing this without having to make my method async?

1 Answers
Related