Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 255
Peter Morris Avatar asked Oct 19 '19 20:10

Peter Morris


1 Answers

I think this is an issue as specified on Github for the Roslyn compiler:

Allow null return from async method when Task<T> type argument is nullable

like image 65
Richard Avatar answered Nov 14 '22 21:11

Richard