Skip to content

Query: Comparing collection navigation to NULL throws Null Exception #5825

Closed

Description

@Feasoron

Steps to reproduce

Have a many to many relationship with a lookup table defined (the odd ID on the lookup is due legacy data we can't change. I don't think it is the issue, but I included it just to be safe)

    public class TableA
    {
        [Key]
        public int TableAId { get; set; }
        public virtual List<TableATableBLookup> TableATableBLookups{ get; set; }
    }

   public class TableATableBLookup
    {
        public int TableATableBLookupId { get; set; }

        public int TableAId { get; set; }
        public TableA{ get; set; }

        public String TableBId{ get; set; }
        public TableB{ get; set; }

        [Column("TableB_FK")]
        public int TableBKey { get; set; }
    }

   public class TableBId
    {
        [Key]
        [Column(TypeName = "nvarchar(450)")]
        public String TableBId{ get; set; }

        public virtual List<TableATableBLookup> TableATableBLookups{ get; set; }

        [Column("TableB_PK")]
        public int TableBKey { get; set; }   
    }

Then I simply try to do a lookup of rows on table a that have at least one row in table b

var rows= _context.TableA
                .Include(l => l.TableATableBLookups)
                .Where(b => b.TableATableBLookups!= null);

When this query is executed, I get an exception

The issue

Exception message:
Value cannot be null. Parameter name: querySource
Stack trace:

   at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.AddQuery(IQuerySource querySource, SelectExpression selectExpression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.RelationalEntityQueryableExpressionVisitor.VisitEntityQueryable(Type elementType)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.EntityQueryableExpressionVisitor.VisitConstant(ConstantExpression constantExpression)
   at System.Linq.Expressions.ConstantExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.ExpressionVisitorBase.Visit(Expression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
   at System.Linq.Expressions.BinaryExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.ExpressionVisitorBase.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.ReplaceClauseReferences(Expression expression, IQuerySource querySource, Boolean inProjection)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitWhereClause(WhereClause whereClause, QueryModel queryModel, Int32 index)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitWhereClause(WhereClause whereClause, QueryModel queryModel, Int32 index)
   at Remotion.Linq.Clauses.WhereClause.Accept(IQueryModelVisitor visitor, QueryModel queryModel, Int32 index)
   at Remotion.Linq.QueryModelVisitorBase.VisitBodyClauses(ObservableCollection`1 bodyClauses, QueryModel queryModel)
   at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](QueryModel queryModel)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass19_0`1.<CompileQuery>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQuery[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Remotion.Linq.QueryableBase`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at EverettWeb.Utilities.LightboxUtility.GetPublicLightboxes()
   at EverettWeb.Controllers.LightboxController.GetHomePageLightboxes()
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.ExecuteAsync(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionExecutor.ExecuteAsync(ObjectMethodExecutor actionMethodExecutor, Object instance, Object[] orderedActionArguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionAsync>d__6.MoveNext()

Further technical details

EF Core version: "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
Operating system: Windows 10 Pro Insider Preview, Build 14361.rs1_release.160603-1700
Visual Studio version: (e.g. VS 2013 or n/a) VS 2015

Other details about my project setup:

Activity

  1. rowanmiller commented on Jun 21, 2016

    @rowanmiller
    Contributor

    Checking for a collection to be equal to null probably isn't what you want, is .Where(b => b.TableATableBLookups.Any()); what you really wanted? We should still fix the null ref exception though.

  2. added this to the 1.1.0 milestone on Jun 21, 2016
  3. Feasoron commented on Jun 21, 2016

    @Feasoron
    Author

    Yes, .Any() does what I need. I should have caught that. Still, I'll keep a branch with the old code on it around in case you need any more details from me.

  4. maumar commented on Aug 26, 2016

    @maumar
    Contributor

    Full standalone repro:

        public class TableA
        {
            public int TableAId { get; set; }
            public virtual List<TableATableBLookup> TableATableBLookups { get; set; }
        }
    
        public class TableATableBLookup
        {
            public int TableATableBLookupId { get; set; }
    
            public int TableAId { get; set; }
            public TableA Foo { get; set; }
    
            public string TableBId { get; set; }
            public TableB Bar { get; set; }
    
            public int TableBKey { get; set; }
        }
    
        public class TableB
        {
            public string TableBId { get; set; }
    
            public virtual List<TableATableBLookup> TableATableBLookups { get; set; }
    
            public int TableBKey { get; set; }
        }
    
        public class MyContext : DbContext
        {
            public DbSet<TableA> TableA { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("Server=.;Database=Repro5825;Trusted_Connection=True;MultipleActiveResultSets=true");
            }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                using (var ctx = new MyContext())
                {
                    ctx.Database.EnsureDeleted();
                    ctx.Database.EnsureCreated();
    
                    var rows = ctx.TableA
                                    .Include(l => l.TableATableBLookups)
                                    .Where(b => b.TableATableBLookups != null).ToList();
                }
            }
        }
  5. maumar commented on Aug 26, 2016

    @maumar
    Contributor

    Reassigning to Smit as he is already working on a similar bug (#6383).

    @smitpatel This bug has slightly different exception, so there might be another issue underneath, make sure to add this scenario to the regression suite once the other bug is fixed, just to make sure

  6. assigned and unassigned on Aug 26, 2016
  7. modified the milestones: , on Oct 5, 2016
  8. assigned and unassigned on Oct 5, 2016
  9. 16 remaining items

  10. MMalikKhan commented on May 8, 2017

    @MMalikKhan

    @maumar, i believe this is fixed now, which version of the EF core, i can find it ? is it already released to current nuget version?

  11. maumar commented on May 8, 2017

    @maumar
    Contributor

    @MMalikKhan It will be available in version 2.0. Sadly fix didn't make to preview1 which is about to get released very soon. So for now, if you want to take advantage of the fix you need to try our nightly builds.

  12. MMalikKhan commented on May 9, 2017

    @MMalikKhan

    @maumar thank you for your quick reply, i changed my implementation from checking for == null to != b.TableATableBLookups.Any() and at the moment i am on 1.1.1 version of EF core and SQLite. It is working as expected without any crash in debug mode, i am hoping it will not have any issues in the release mode as well.

    Any suggestions if this change will work in all of the cases ?

    `class Program
    {
    static void Main(string[] args)
    {
    using (var ctx = new MyContext())
    {
    ctx.Database.EnsureDeleted();
    ctx.Database.EnsureCreated();

                var rows = ctx.TableA
                                .Include(l => l.TableATableBLookups)
                                .Where(b => !b.TableATableBLookups.Any() ).ToList();
            }
        }
    }`
    
  13. maumar commented on May 9, 2017

    @maumar
    Contributor

    If you want to entities for which TableATableBLookups table is not empty then the code snipped you provided is the right way to do it, and it should work in all cases (debug and release).

    The bugfix specifically handles cases where the collection navigation is compared directly to null. In the new implementation we will rewrite:

    b.TableATableBLookups != null
    

    into:

    b != null
    

    (i.e. we assume that collection is only null if it's parent entity is null)

    but at the same time issue a warning that this may not be what you wanted, and that you should use .Any() if the intention was to check if collection is not empty. `

  14. MMalikKhan commented on May 9, 2017

    @MMalikKhan

    @maumar Thank you !! Agree with your comments.

  15. modified the milestones: 2.0.0, on May 16, 2017
  16. modified the milestones: , 2.0.0 on Oct 15, 2022
  17. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions