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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With