Home > OS >  Visual Studio assumes return value from FirstOrDefaultAsync() cannot be null
Visual Studio assumes return value from FirstOrDefaultAsync() cannot be null

Time:10-30

I have the following query.

var railcarInfo = await (from rt in DbContext.RailcarTrips
                         where rt.WaybillRailcar.RailcarNumber == clm.RailcarNumber &&
                         rt.WaybillRailcar.Waybill.CreateDate <= clm.SightingDate
                         orderby rt.WaybillRailcar.Waybill.CreateDate descending
                         select new
                         {
                             RailcarTrip = rt,
                             WaybillCreateDate = rt.WaybillRailcar.Waybill.CreateDate,
                             IsLoaded = rt.WaybillRailcar.Weight > 0
                         })
                         .AsNoTracking()
                         .FirstOrDefaultAsync();

But for some reason, Visual Studio decides that 'railcarInfo' is not null here immediately following this query.

enter image description here

The point of FirstOrDefaultAsync() is that it returns the first item in a collection, or null if the collection is empty. It could definitely be null here. Can anyone see why Visual Studio seems to get confused here?

CodePudding user response:

As mentioned in docs about this feature and EF:

Prior to EF Core 6.0, the public API surface wasn't annotated for nullability (the public API was "null-oblivious"), making it sometimes awkward to use when the NRT feature is turned on. This notably includes the async LINQ operators exposed by EF Core, such as FirstOrDefaultAsync. The public API is fully annotated for nullability starting with EF Core 6.0.

So you likely using version of EF < 6.0

  • Related