I have this linq query. It complains with the warning message.
Warning CS8603 Possible null reference return
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.
CodePudding user response:
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:
- This method can return null, then change the signature to
Task<Pie?>
to let calling code know that it can return null. - This method shouldn't return null, use
SingleAsync(...)
so that it will throw a runtime exception if no matchingid
is found.
CodePudding user response:
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, you 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.