efcore icon indicating copy to clipboard operation
efcore copied to clipboard

NullReferenceException in big query?

Open kierepka opened this issue 10 years ago • 11 comments

Steps to reproduce

Create big query with subqueries give NullReferenceException. Sample below

The issue

Quite big linq query is working ok on EF6 but EFCore give NullReferenceException

q =  (from d in db.Doctors
from dpm in d.DoctorPatientMaps
join p in db.Patients on dpm.PatientId equals p.Id
join r in db.Readings on p.Id equals r.PatientId
join o in db.Orders on r.Id equals o.ReadingId into lor
from os in lor.DefaultIfEmpty()
join m in db.MedicalFacilities on os.MedicalFacilityId equals m.Id into lms
from ms in lms.DefaultIfEmpty()
join rd in db.ReadingDescriptions on r.Id equals rd.ReadingId into lrds
from rds in lrds.DefaultIfEmpty()
orderby r.LastUpdateDate descending
where d.Id == doctorId.Value && (includeEmergency ? (!r.IsEmergency || r.IsEmergency == d.CanSeeEmergency) : !r.IsEmergency)
            && (!r.IsDemo || r.IsDemo == d.CanSeeDemo)
select new
{
    Id = r.Id,
    ReadingAddDate = r.ReadingAddDate,
    ReadingStartDate = r.ReadingStartDate,
    ReadingEndDate = r.ReadingEndDate,
    PatientId = r.PatientId,
    DataPath = r.DataPath,
    ExamFileName = r.ExamFileName,
    Type = r.Type,
    Status = r.Status,
    Comment = r.Comment,
    PaperOffsetSpeed = r.PaperOffsetSpeed,
    Gain = r.Gain,
    DeviceId = r.DeviceId,
    CanBeChanged = r.CanBeChanged,
    DoctorIdInExam = r.DoctorIdInExam,
    Data = r.Data,
    LastUpdateDate = r.LastUpdateDate,
    IsEmergency = r.IsEmergency,
    PreinterpretedRecognition = r.PreinterpretedRecognition,
    DoctorUuid = r.DoctorUuid,
    IsProcessed = r.IsProcessed,
    VersionOfTheAlgorithm = r.VersionOfTheAlgorithm,
    SourceFilename = r.SourceFilename,
    IsSentToDescription = r.IsSentToDescription,
    Mood = r.Mood,
    SampleRate = r.SampleRate,
    ReadingRootId = r.ReadingRootId,
    EndDescriptionDate = r.EndDescriptionDate,
    IsContainsAnyRaport = r.IsContainsAnyRaport,
    IsDemo = r.IsDemo,
    IsCanceled = r.IsCanceled,
    IsDeleted = r.IsDeleted,
    ApplicationVersion = r.ApplicationVersion,
    ReadingTypeId = r.ReadingTypeId,
    OrderId = (int?)os.Id,
    OrderDateTime = (DateTime?)os.DateTime,
    OrderMaxDescriptionTime = (int?)os.MaxDescriptionTime,
    OrderMedicalFacilityName = ms.Name,
    MedicalFacilityId = (int?)ms.Id,
    IsDescribed = ((int?)rds.Id).HasValue,
    IsAllEventsAreConfirmed = (from rres in db.ReadingEvents
                                where rres.Status == "NP" && rres.ReadingId == r.Id
                                select rres.Id).Count() == 0,
    IsRootToOrders = (from r3 in db.Readings
                        where r3.ReadingRootId == r.Id
                        select r3.Id).Count() != 0

});

Exception message:

System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=Anonymously Hosted DynamicMethods Assembly StackTrace: at lambda_method(Closure , TransparentIdentifier2 ) at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)

Further technical details

EF Core version: version="1.0.0" Operating system: Windows 10/Server Visual Studio version: VS 2015

Other details about my project setup: IIS ASP.NET Web

kierepka avatar Aug 09 '16 17:08 kierepka

This same query in LinqPad also is working and give this TSQL:

-- Region Parameters
DECLARE @p0 Int = 39
DECLARE @p1 Int = 0
DECLARE @p2 NVarChar(1000) = 'NP'
DECLARE @p3 Int = 0
DECLARE @p4 Int = 0
-- EndRegion
SELECT [t3].[Id], [t3].[ReadingAddDate], [t3].[ReadingStartDate], [t3].[ReadingEndDate], [t3].[PatientId], [t3].[DataPath], [t3].[ExamFileName], [t3].[Type], [t3].[Status], [t3].[Comment], [t3].[PaperOffsetSpeed], [t3].[Gain], [t3].[DeviceId], [t3].[CanBeChanged], [t3].[DoctorIdInExam], [t3].[Data], [t3].[LastUpdateDate], [t3].[IsEmergency], [t3].[PreinterpretedRecognition], [t3].[DoctorUuid], [t3].[IsProcessed], [t3].[VersionOfTheAlgorithm], [t3].[SourceFilename], [t3].[IsSentToDescription], [t3].[Mood], [t3].[SampleRate], [t3].[ReadingRootId], [t3].[EndDescriptionDate], [t3].[IsContainsAnyRaport], [t3].[IsDemo], [t3].[IsCanceled], [t3].[IsDeleted], [t3].[ApplicationVersion], [t3].[ReadingTypeId], [t4].[Id] AS [OrderId], [t4].[DateTime] AS [OrderDateTime], [t4].[MaxDescriptionTime] AS [OrderMaxDescriptionTime], [t5].[Name] AS [OrderMedicalFacilityName], [t5].[Id] AS [MedicalFacilityId], 
    (CASE 
        WHEN ([t6].[Id]) IS NOT NULL THEN 1
        ELSE 0
     END) AS [IsDescribed], 
    (CASE 
        WHEN ((
            SELECT COUNT(*)
            FROM [ReadingEvents] AS [t8]
            WHERE ([t8].[Status] = @p2) AND ([t8].[ReadingId] = [t3].[Id])
            )) = @p3 THEN 1
        WHEN NOT (((
            SELECT COUNT(*)
            FROM [ReadingEvents] AS [t8]
            WHERE ([t8].[Status] = @p2) AND ([t8].[ReadingId] = [t3].[Id])
            )) = @p3) THEN 0
        ELSE NULL
     END) AS [IsAllEventsAreConfirmed], 
    (CASE 
        WHEN ((
            SELECT COUNT(*)
            FROM [Readings] AS [t10]
            WHERE [t10].[ReadingRootId] = ([t3].[Id])
            )) <> @p4 THEN 1
        WHEN NOT (((
            SELECT COUNT(*)
            FROM [Readings] AS [t10]
            WHERE [t10].[ReadingRootId] = ([t3].[Id])
            )) <> @p4) THEN 0
        ELSE NULL
     END) AS [IsRootToOrders]
FROM [Doctors] AS [t0]
CROSS JOIN [DoctorPatientMaps] AS [t1]
INNER JOIN [Patients] AS [t2] ON [t1].[PatientId] = [t2].[Id]
INNER JOIN [Readings] AS [t3] ON ([t2].[Id]) = [t3].[PatientId]
LEFT OUTER JOIN [Orders] AS [t4] ON [t3].[Id] = [t4].[ReadingId]
LEFT OUTER JOIN [MedicalFacilities] AS [t5] ON [t4].[MedicalFacilityId] = [t5].[Id]
LEFT OUTER JOIN [ReadingDescriptions] AS [t6] ON [t3].[Id] = [t6].[ReadingId]
WHERE ([t0].[Id] = @p0) AND ((
    (CASE 
        WHEN @p1 = 1 THEN 
            (CASE 
                WHEN (NOT ([t3].[IsEmergency] = 1)) OR ([t3].[IsEmergency] = [t0].[CanSeeEmergency]) THEN 1
                WHEN NOT ((NOT ([t3].[IsEmergency] = 1)) OR ([t3].[IsEmergency] = [t0].[CanSeeEmergency])) THEN 0
                ELSE NULL
             END)
        ELSE CONVERT(Int,
            (CASE 
                WHEN NOT ([t3].[IsEmergency] = 1) THEN 1
                WHEN NOT NOT ([t3].[IsEmergency] = 1) THEN 0
                ELSE NULL
             END))
     END)) = 1) AND ((NOT ([t3].[IsDemo] = 1)) OR ([t3].[IsDemo] = [t0].[CanSeeDemo])) AND ([t1].[DoctorId] = [t0].[Id])
ORDER BY [t3].[LastUpdateDate] DESC

kierepka avatar Aug 09 '16 17:08 kierepka

@kierepka is there any chance you could single out what part of the query is producing the exception? We suspect this could be due to one of the joins triggering client-side evaluation. When evaluating on the client, trying to access a property on a null object will produce this exception.

divega avatar Aug 10 '16 18:08 divega

I am having this same exception when creating the Expressions dynamically to a "sub-entity" that could possibly null.

SELECT * FROM x LEFT OUTER JOIN y ON y.XId = x.Id WHERE y.Text LIKE '%A%'

This works in sql, but creating the same query dynamically in EF7 gives this exception above, but works in EF6.3 without issues using the same code to create the dynamic expression.

Just found the issue this morning, glad to see I am not the only person with it.

EDIT https://github.com/aspnet/EntityFramework/issues/4002

At the bottom says to do a null check on the sub-entity before actually doing the check. I am going to try to add this in code to see if will correct my issues and will let you know if it works.

EDIT Doesn't work, I removed creating the expression dynamically and tried it directly and had the same issue.

this.Entity .Include(x => x.Requestor) .FirstOrDefault(x => x.Requestor != null && x.Requestor.ActiveDirectoryFriendlyName.Contains("test"));

Requestor in this case is a left outer join, and I added the null check as well and throws the same error.

So we will be sticking with EF6 until this issue is resolved for we can find a work around. We use this type of lambda expression alot in our generic expression.

rpannell avatar Aug 11 '16 14:08 rpannell

Triage: it seems that both the initial report and the previous comment are very similar to #4002 (which we closed as by design) in which NullReferenceException ends up being thrown because of a null navigation property referenced in the query is evaluated in memory.

I see two things we need to follow up on:

  • The previous comment implies that explicily adding defensive null checks doesn't help,
  • We have been talking about approaching differently so that when in memory nulls get propagated in a similar way to how they are in the database, e.g. we can add the null checks for navigation property rewrites and other similar cases.

divega avatar Aug 15 '16 16:08 divega

Related #6129 in which a NullReferenceException occurs, not because of a null navigation property but because of a null parameter.

divega avatar Aug 15 '16 16:08 divega

Hello, When is this issue going to be resolved?

devseal avatar Aug 17 '16 03:08 devseal

@jjanne check the Milestone, 1.1.0.

gdoron avatar Aug 17 '16 04:08 gdoron

Could this error be related to what I am getting?

SELECT [b].[Id], [b].[AddressLine1], [b].[AddressLine2], [b].[BillingCurrencyCode], [b].[BusinessName], [b].[City], [b].[ContactName], [b].[CountryCode], [b].[CreatedOn], [b].[IsTestBusiness], [b].[ModifiedOn], [b].[PaymentType], [b].[PhoneNumber], [b].[PostalCode], [b].[Region], [b].[RowVersion], [b].[TimeZoneId]
FROM [Auth].[Business] AS [b]
WHERE [b].[Id] = @__businessId_0
ORDER BY [b].[Id]
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory:Information: Executed DbCommand (0ms) [Parameters=[@__businessId_0='?'], CommandType='Text', CommandTimeout='30']
SELECT [u].[Id], [u].[BusinessId], [u].[CreatedOn], [u].[DeclarantCode], [u].[DeclarantPin], [u].[ModifiedOn], [u].[RowVersion], [u].[UserId], [u].[UserStatus]
FROM [Auth].[UserBusiness] AS [u]
WHERE EXISTS (
    SELECT 1
    FROM [Auth].[Business] AS [b]
    WHERE ([b].[Id] = @__businessId_0) AND ([u].[BusinessId] = [b].[Id]))
ORDER BY [u].[BusinessId], [u].[Id]
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory:Information: Executed DbCommand (1ms) [Parameters=[@__businessId_0='?'], CommandType='Text', CommandTimeout='30']
SELECT [a].[Id], [a].[BusinessAppId], [a].[CreatedOn], [a].[UserBusinessId]
FROM [Auth].[AppAccess] AS [a]
INNER JOIN (
    SELECT DISTINCT [u].[BusinessId], [u].[Id]
    FROM [Auth].[UserBusiness] AS [u]
    WHERE EXISTS (
        SELECT 1
        FROM [Auth].[Business] AS [b]
        WHERE ([b].[Id] = @__businessId_0) AND ([u].[BusinessId] = [b].[Id]))
) AS [u0] ON [a].[UserBusinessId] = [u0].[Id]
ORDER BY [u0].[BusinessId], [u0].[Id]
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection:Debug: Closing connection to database 'SpeediAuth' on server '(localdb)\mssqllocaldb'.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.0\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.0\System.IO.MemoryMappedFiles.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.0\System.IO.UnmanagedMemoryStream.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory:Error: An exception occurred in the database while iterating the results of a query.
System.ArgumentNullException: Value cannot be null.
System.ArgumentNullException: Value cannot be null.
Parameter name: source
   at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityTrackingInfo.<GetIncludedEntities>d__17.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityTrackingInfo.<GetIncludedEntities>d__17.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__157`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.StartTracking(Object entity, EntityTrackingInfo entityTrackingInfo)
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__15`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Speedi.Auth.Data.SqlServer.Repository.BusinessRepository.<GetBusinessAsync>d__3.MoveNext() in C:\gitrepos\SpeediAuth\src\Speedi.Auth.Data.SqlServer\Repository\BusinessRepository.cs:line 37
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Speedi.Auth.Web.Mvc.Services.BusinessServices.BusinessService.<GetAcceptanceUrlForUserInvitationAsync>d__14.MoveNext() in C:\gitrepos\SpeediAuth\src\Speedi.Auth.Web.Mvc\Services\BusinessServices\BusinessService.cs:line 137}

Caused by a simple include - then include query

var business = _context.Businesses
                .Include(b => b.UserBusinesses)
                .ThenInclude(ub => ub.AppAccesses) //If i remove this line it's all good. Why?
                .Where(b => b.Id == businessId)
                .ToList();

businessId is a Guid type in case this has anything to do with the issue when joining tables.

I tried with the nightly "1.1.0-alpha1-21937" and the problem is still there.

iberodev avatar Aug 23 '16 05:08 iberodev

@kierepka could you share your model as well? You can either post it here or send it to me privately on email - [my_github_alias][at]microsoft[d0t]com. If you decide to send it via email, please also let me know here, in case spam filters decide to eat emails from outside of microsoft.

maumar avatar Aug 31 '16 22:08 maumar

clearing milestone for re-triage as we haven't heard from a customer for a long time

maumar avatar Sep 30 '16 18:09 maumar

EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.

rowanmiller avatar Oct 03 '16 18:10 rowanmiller