I have this linq query. It complains with the warning message.
Warning CS8603: Possible null reference return
Code:
return await _applicationDbContext.Pies
.Include(x => x.Portions).AsSingleQuery()
.Include(x => x.Ingredients).AsSplitQuery()
.SingleOrDefaultAsync(x => x.Id == id);
Further more this is making it ugly with squiggles all over.
Can anything be done about it?
Looked at the following SO posts, but could not figure out what to do.
understanding Possible null reference return
Understanding the new nullable reference types warning
SingleOrDefaultAsync()
does exactly what's in the method name, it tries to find a single entry and returns the default if nothing is found.
The default for a reference type, your object Pie
in this case, is null hence the warning.
You can either return Task<Pie?>
or instead handle the null value in some way. One way would be to use .SingleAsync()
instead, which will throw if nothing was found - but therefore it will never return null.
The method returns a Task<Pie>
.
The return ...
has SingleOrDefaultAsync(...)
at the end which means if it cannot find an item with a matching id
it will return default(Pie)
which will be null
.
You need to decide if either:
Task<Pie?>
to let calling code know that it can return null.SingleAsync(...)
so that it will throw a runtime exception if no matching id
is found.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