Search code examples
c#linq

possible null reference return c# linq


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.


Solution

  • 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.