possible null reference return c# linq

Viewed 444

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?

Vs 2022 Warning message

Looked at the following SO posts, but could not figure out what to do.

2 Answers

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.

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:

  1. This method can return null, then change the signature to Task<Pie?> to let calling code know that it can return null.
  2. This method shouldn't return null, use SingleAsync(...) so that it will throw a runtime exception if no matching id is found.
Related