efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Null Reference when using AS in ternary in EF Projection

Open EddyPPP opened this issue 8 years ago • 9 comments

I have a derived class with a nullable reference property. My DbContext surfaces a DbSet of a base class. If I try to optionally cast it in a ternary, I get the following error:

Exception message:
Object reference not set to an instance of an object.
Stack trace:
   at Microsoft.EntityFrameworkCore.Extensions.Internal.EFPropertyExtensions.CreateEFPropertyExpression(Expression target, Type propertyDeclaringType, Type propertyType, String propertyName, Boolean makeNullable)
   at Microsoft.EntityFrameworkCore.Extensions.Internal.EFPropertyExtensions.CreateEFPropertyExpression(Expression target, IPropertyBase property, Boolean makeNullable)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.EntityEqualityRewritingExpressionVisitor.CreateKeyAccessExpression(Expression target, IReadOnlyList`1 properties, Boolean nullComparison)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.EntityEqualityRewritingExpressionVisitor.RewriteNullEquality(ExpressionType nodeType, Expression nonNullExpression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.EntityEqualityRewritingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at System.Linq.Expressions.BinaryExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitConditional(ConditionalExpression node)
   at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitConditional(ConditionalExpression node)
   at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Remotion.Linq.Clauses.SelectClause.TransformExpressions(Func`2 transformation)
   at Remotion.Linq.QueryModel.TransformExpressions(Func`2 transformation)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryOptimizer.Optimize(QueryCompilationContext queryCompilationContext, QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.OptimizeQueryModel(QueryModel queryModel, Boolean asyncQuery)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.OptimizeQueryModel(QueryModel queryModel, Boolean asyncQuery)
   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 Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, IQueryModelGenerator queryModelGenerator, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass13_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   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.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at AsTernaryIssue.Program.Main(String[] args) in C:\....\AsTernaryIssue\Program.cs:line 45

Steps to reproduce

Sample project demonstrating the simplest example attached: AsTernaryIssue.zip

Summary is:

DBContext:

 public class MyDbContext : DbContext
    {
        public DbSet<BaseClass> Entities { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=.\\SQLSERVER2017DEV; Database=Example; Trusted_Connection=true;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<DerivedClass>();
        }
    }

Derived Model:

public class DerivedClass : BaseClass
    {
        public Guid? ChildId { get; set; }
        public virtual ChildClass Child { get; set; }
    }

Now run this query:

db.Entities.AsNoTracking()
                    .Select(x =>
                        x is DerivedClass ?
                        (
                            (x as DerivedClass).Child != null ?
                            (x as DerivedClass).Child.Name :
                            String.Empty
                        ) :
                        String.Empty
                    )
                    .ToList()

Further technical details

EF Core version: 2.1 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Visual Studio 2017 15.7.3

EddyPPP avatar Jun 06 '18 11:06 EddyPPP

Many thanks for taking a look - do you have any ballpark as to when 2.1.3 might be released? Also, can you think of any alternate ways I could express the query to avoid the error? I'm just trying to plan whether to workaround for now, downgrade again, or wait.

EddyPPP avatar Jun 13 '18 09:06 EddyPPP

@EddyPPP 2.1.3 is tentatively scheduled for August, but that could easily change.

ajcvickers avatar Jun 14 '18 17:06 ajcvickers

@EddyPPP - Did it give correct results in prior release of EF? We are client eval the predicate here but predicate uses a navigation property which won't get expanded so (x as DerivedClass).Child is always going to be null.

smitpatel avatar Jun 14 '18 19:06 smitpatel

Triage: given that this didn't function correctly in 2.0 we do not want to revert back to that behavior. @smitpatel to document workarounds.

ajcvickers avatar Jun 15 '18 21:06 ajcvickers

Since the where predicate is complex enough that we cannot translate it to server. work-around query:

        db.Entities.AsNoTracking().Include(x => ((DerivedClass)x).Child).ToList()
                    .Select(x =>
                        x is DerivedClass ?
                        (
                            (x as DerivedClass).Child != null ?
                            (x as DerivedClass).Child.Name :
                            String.Empty
                        ) :
                        String.Empty
                    )
                    .ToList()

smitpatel avatar Jun 19 '18 18:06 smitpatel

Hi @smitpatel & @ajcvickers - Thanks for looking at this and apologies for the delay, I had a long weekend.

I can confirm that this behaviour WAS working in 2.0 - indeed it was only after the upgrade to 2.1 that my existing working queries started erroring.

In the example I provided, x.Child would always be null - simply because this demonstrates the problem in the quickest way. In my real-world app the property may or may not be null, and I have an .Include() that hydrates it.

I was trying to avoid hydrating with a .ToList before applying the predicate because I also use this kind of logic to apply where clauses before I page the data. Without this being capable of being translated server-side, I cannot use it in a where clause and apply paging. I would need to retrieve the entire dataset into memory before executing the returning the top 10 rows.

I have attached the same code as a 2.0 project, and it works as expected.

AsTernaryIssue.zip

EddyPPP avatar Jun 19 '18 19:06 EddyPPP

I downloaded that repro code and ran it (with updating SqlServer connection string, no other change) I got following output

D:\code\AsTernaryIssue\AsTernaryIssue> dotnet run
Checking DB is up to date
Adding derived Class that has a Child
Adding derived Class that does not have a Child
Finding all the Child Names
1
1

That is what we are referring to when we said the behavior did not work. Even though one of the DerivedClass has a Child in database, we are not printing out its name. The query prints 1 always, as if the Child navigation is null. And that happens because when the query is evaluated on client, the navigation will not be populated. (see #10471). Further since it is client eval, it is going to fetch whole table even with skip/take.

The work-around query I posted does the same thing (no additional data fetched). Another (untested) work-around would be to use hard cast rather than as operator.

smitpatel avatar Jun 19 '18 20:06 smitpatel

Thanks @smitpatel, but as I mentioned before - the lack of an Include was simply to demonstrate the issue (and actually to ensure a null) - this is example code that I mocked up for the purpose of demonstrating the minimum code needed to surface the issue, not the final production code!

To avoid ambiguity, I have included 2.0 and 2.1 apps with a WHERE, TAKE, and INCLUDE: 2.0.zip 2.1.zip

The SAME query works on 2.0, but does not on 2.1.

EddyPPP avatar Jun 20 '18 12:06 EddyPPP

Closing as dupe of #10471. (There are several things mentioned here covered in several different issues elsewhere, by 10471 seems reasonable to choose as the dupe.)

ajcvickers avatar Jun 27 '18 20:06 ajcvickers