Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EFCore throws NullReferenceException when include is called. #11153

Closed
onlyanup opened this issue Mar 5, 2018 · 3 comments
Closed

EFCore throws NullReferenceException when include is called. #11153

onlyanup opened this issue Mar 5, 2018 · 3 comments

Comments

@onlyanup
Copy link

onlyanup commented Mar 5, 2018

When I call the ToListAsync() method after including a collection, it throws the NullReferenceException. The error doesn't occur when there is no include.

Stack trace:
NullReferenceException: Object reference not set to an instance of an object.
lambda_method(Closure , AnonymousObject )
System.Linq.Internal.Lookup+d__16.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+JoinAsyncIterator+d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+AsyncIterator+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+<Aggregate_>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.OrderedAsyncEnumerable+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.OrderedAsyncEnumerable+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.OrderedAsyncEnumerable+d__9.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+AsyncIterator+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+SelectEnumerableAsyncIterator+d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
System.Linq.AsyncEnumerable+AsyncIterator+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler+<_IncludeAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.TaskLiftingExpressionVisitor+<ExecuteAsync>d__8.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+AsyncSelectEnumerable+AsyncSelectEnumerator+d__3.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
System.Linq.AsyncEnumerable+SelectEnumerableAsyncIterator+d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
System.Linq.AsyncEnumerable+AsyncIterator+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor+EnumeratorExceptionInterceptor+d__5.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
System.Linq.AsyncEnumerable+<Aggregate
>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
App.Db.DbOps+d__19.MoveNext() in DbOps.cs

            if (includableQuery == null)
            {
                var data = await orderedQuery.ToListAsync();
                return (data.Count, data);
            }
            else
            {
                var data = await includableQuery.ToListAsync();
                return (data.Count, data);
            }
        }
        //else send data according to its page number and page size along with the total number of data available
        return (

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
App.Objective.Controllers.ProjectItemController+d__1.MoveNext() in ProjectItemController.cs

    public ProjectItemController(AppDbContext dbContext, IUserDependency user) : base(dbContext, user.User.UserId)
    {
    }
    public async override Task<(int, IEnumerable<ProjectItem>)> Get(string query)
    {
        return await Ops.GetAsync(true, includeInactive: true, includeProperty: t => t.MoreProperties);
    }

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

Steps to reproduce

Create a web API project. Create connected(via foreign key attribute) tables and add to the context. then query using this function

/// <summary>
        /// Gets the list of items asynchronously
        /// </summary>
        /// <param name="allData">if set to <c>true</c> then all the data will be shown in one go. Use with care as it may take some time to get million objects.</param>
        /// <param name="pageNumber">The page number of the request.</param>
        /// <param name="pageSize">Size of the page you want to get.</param>
        /// <param name="includeInactive">if set to <c>true</c> then inactive data will also come. if set to <c>false</c> then only active data will be shown. To see only inactive, pass false here and frame your <paramref name="conditions" /></param>
        /// <param name="showTrashed">if set to <c>true</c> then only trashed data will be shown else only live data will be considered</param>
        /// <param name="conditions">The condition to go inside where clause.</param>
        /// <param name="ascendingOrder">if set to <c>true</c> then the ordering will be done in ascending.</param>
        /// <param name="OrderBy">The order by property</param>
        /// <param name="includeProperty">The property to be included in the query.</param>
        /// <returns>The total count of data and the list of data</returns>
        /// query accordingly
        public virtual async Task<(int, List<T>)> GetAsync(bool allData, int pageNumber = 1, int pageSize = 10, bool includeInactive = false, bool showTrashed = false, Expression<Func<T, bool>> conditions = null, bool ascendingOrder = false, Expression<Func<T, object>> OrderBy = null, Expression<Func<T, object>> includeProperty = null)
        {
            //check if its trashed data or live data to be shown
            var query = Table.Where(q => q.Trashed == showTrashed);

            //check if we need to show the inactive data as well
            if (!includeInactive)
            {
                //show only active data here
                query = query.Where(q => q.Active == true);
            }

            //check if condition is not null
            if (conditions != null)
            {
                //so that we can plug-in more filters
                query = query.Where(conditions);
            }

            //create a variable to store ordered query
            IOrderedQueryable<T> orderedQuery;

            //check if ordered by has not been passed
            if (OrderBy == null)
            {
                //meaning default order by which is by created date. Check the direction and plug it in
                if (ascendingOrder)
                {
                    orderedQuery = query.OrderBy(t => t.CreatedOn);
                }
                else
                {
                    orderedQuery = query.OrderByDescending(t => t.CreatedOn);
                }
            }

            //so order by has been passed
            else
            {
                //plug-in as required in order direction
                if (ascendingOrder)
                {
                    orderedQuery = query.OrderBy(OrderBy);
                }
                else
                {
                    orderedQuery = query.OrderByDescending(OrderBy);
                }
            }

            //create a variable to store included query
            IIncludableQueryable<T, object> includableQuery = null;

            //check if include request is provided
            if (includeProperty != null)
            {
                //include the included property
                includableQuery = orderedQuery.Include(includeProperty);
            }
            //check if all data is required in one go
            if (allData)
            {
                //send all data
                if (includableQuery == null)
                {
                    var data = await orderedQuery.ToListAsync();
                    return (data.Count, data);
                }
                else
                {
                    var data = await includableQuery.ToListAsync();
                    return (data.Count, data);
                }
            }
            //else send data according to its page number and page size along with the total number of data available
            return (
                //get the count
                includableQuery == null ? orderedQuery.Count() : includableQuery.Count(),
                //get the data
                await (includableQuery == null ?
                orderedQuery.Skip(pageSize * (pageNumber - 1)).Take(pageSize).ToListAsync() :
                includableQuery.Skip(pageSize * (pageNumber - 1)).Take(pageSize).ToListAsync()));
        }

public DbSet<T> Table { get; private set; }
public Context Db { get; private set; }

private DbSet<T> GetCompleteTableInfo(Context dbContext)
        {
            //getting the property of the current model T
            var prop = dbContext.GetType().GetProperties().Where(t => t.PropertyType == typeof(DbSet<T>)).FirstOrDefault();
            if (prop == null)
            {
                throw new Exception("The model is not added in the context");
            }
            //return all the data of this model
            return (DbSet<T>)prop.GetValue(Db);
        }

/// <summary>
        /// Initializes a new instance of the <see cref="DbOps{T}"/> class.
        /// </summary>
        /// <param name="DbContext">The database context.</param>
        /// <param name="userId">The user identifier.</param>
        public DbOps(Context DbContext, Guid userId)
        {
            Db = DbContext;
            UserId = userId;
            Table = GetCompleteTableInfo(DbContext);
        }

Error occurs in the method GetAsync when I provide the value of includeProperty parameter

Further technical details

EF Core version: 2.0
Database Provider: (localdb)\MSSQLLocalDB
Operating system: Windows 10 Pro
IDE: Visual Studio 2017 15.5.7

@ajcvickers
Copy link
Contributor

This is a duplicate of #9038, which is already fixed and released in the 2.0.1 patch of EF Core (released as part of the 2.0.3 all-up ASP.NET Core patch release.)

@SabirHossain
Copy link

Sometimes this happen when you have a null value in your DB column which is bind to a non-nullable property.
Ex.
In DB > (MyProperty = null)
In Model > public bool MyProperty {get; set;}

Solutaion:
public bool? MyProperty {get; set;}

@professor-k
Copy link

In my case after adding one explicit .Include() implicit includes by navigation properties got broken, hence NRE. Fixed by adding them explicitly too, though it took me some time to figure out the case.

WeihanLi added a commit to WeihanLi/WeihanLi.EntityFramework that referenced this issue Jul 1, 2019
@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants