efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Incorrect SQL Generation: Missing parenthesis with Contains() and nullable collections

Open swt-das opened this issue 9 years ago • 4 comments

In a Where of the form Where(e => SomeCheck && nullableList.Contains(e.SomeNullableProperty) the generated SQL code is missing parenthesis therefore generating incorrect results.

Assume an entity like:

public sealed class Entity
{
    public int EntityId { get; set; }
    public DateTime Date { get; set; }
   public int? SomeValue { get; set; }
}

and the following LINQ:

var myIds = new int?[]
{
       null, 
       100
};
var result = await ctx.Entities.Where(e => e.Date >= new DateTime(2017, 1, 1) && 
                                               myIds.Contains(e.SomeValue)).ToListAsync();

This generates:

SELECT [e].[EntityId], [e].[Date], [e].[SomeValue]
FROM [Entities] AS [e]
WHERE ([e].[Date] >= '2017-01-01T00:00:00.000') AND [e].[SomeValue] IN (100) OR [e].[SomeValue] IS NULL

which is missing parenthesis around [e].[SomeValue] IN (100) OR [e].[SomeValue]. Due to this, every entry where SomeValue is null is returned, independent what the Date is.

Further technical details

EF Core version: 1.1.1 Database Provider: Microsoft.EntityFrameworkCore.SqlServer 1.1.1 Operating system: Windows 10 IDE: Visual Studio 2017 Enterprise

Steps to reproduce

Full console solution to reproduce the issue. The interesting part is at line 39 where we see that an entity is returned with DateTime 2016-01-01. The expected result would be an empty result.

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;

namespace DotNetCoreTest
{
    public static class DbContextExtensions
    {
        public static void LogToConsole(this DbContext context)
        {
            var serviceProvider = context.GetInfrastructure();
            var loggerFactory = (ILoggerFactory)serviceProvider.GetService(typeof(ILoggerFactory));
            loggerFactory.AddProvider(new EFLoggerProvider());
        }
    }

    internal static class Program
    {
        static void Main(string[] args)
        {
            MainInternal().GetAwaiter().GetResult();
        }

        private static async Task MainInternal()
        {
            await InitDb();
            using (var ctx = new MyContext())
            {
                var myIds = new int?[]
                {
                    null, 
					100
                };
                var result = await ctx.Entities.Where(e => e.Date >= new DateTime(2017, 1, 1) && myIds.Contains(e.SomeValue)).ToListAsync();
                // This should be 0 but is 1. The result includes the entity with date 2016 despite the limiting where above
                Console.WriteLine(result.Count); 
                result.ForEach(Console.WriteLine); 
            }
        }

        private static async Task InitDb()
        {
            using (var ctx = new MyContext())
            {
                ctx.LogToConsole();
                ctx.Database.EnsureCreated();
                if (await ctx.Entities.AnyAsync())
                {
                    return;
                }
                await ctx.Entities.AddRangeAsync(new[]
                {
                    new Entity()
                    {
                        Date = new DateTime(2017, 1, 1),
                        SomeValue = 0xdead
                    },
                    new Entity()
                    {
                        Date = new DateTime(2016, 1, 1),
                        SomeValue = null
                    }
                });
                await ctx.SaveChangesAsync();
            }
        }
    }

    public sealed class MyContext : DbContext
    {
        public DbSet<Entity> Entities { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=TestDb;Trusted_Connection=True;MultipleActiveResultSets=true;");
        }
    }

    public sealed class Entity
    {
        public int EntityId { get; set; }

        public DateTime Date { get; set; }

        public int? SomeValue { get; set; }

        public override string ToString()
        {
            return $"{Date} - {SomeValue?.ToString() ?? "NULL"}";
        }
    }

    public class EFLoggerProvider : ILoggerProvider
    {
        public ILogger CreateLogger(string categoryName)
        {
            if (categoryName == typeof(IRelationalCommandBuilderFactory).FullName)
            {
                return new EFLogger();
            }
            return new NullLogger();
        }

        public void Dispose()
        {
            // N/A
        }

        private class NullLogger : ILogger
        {
            public bool IsEnabled(LogLevel logLevel)
            {
                return false;
            }

            public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
            { }

            public IDisposable BeginScope<TState>(TState state)
            {
                return null;
            }
        }


        private class EFLogger : ILogger
        {
            public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
            {
                Console.WriteLine(formatter(state, exception));
            }

            public bool IsEnabled(LogLevel logLevel)
            {
                return true;
            }

            public IDisposable BeginScope<TState>(TState state)
            {
                return null;
            }
        }
    }
}

swt-das avatar Apr 27 '17 16:04 swt-das

this is legitimate bug and it repros in the current code

maumar avatar Apr 27 '17 20:04 maumar

Problem is that currently Contains with on array with null value(s) is converted into OrElse(InExpression, IsNullExpression) and revisited. SqlGen assumes parens are not needed for this case (we only add them if the left side of binary expression is another binary expression).

Instead of this approach (rewrite and revisit) we should handle the InExpression translation right away (or perhaps add some state to the InExpression itself, rather than involving a binary)

maumar avatar Apr 27 '17 21:04 maumar

For the time being, here is a workaround by doing the contains-null-check on the client beforehand:

var myIds = new List<int?>
{
       null, 
       100
};

var containsNull = myIds.Contains(null);
if(containsNull)
    myIds.Remove(null);

var result = await ctx.Entities
    .Where(e => 
        e.Date >= new DateTime(2017, 1, 1) && 
        (containsNull && e.SomeValue == null || myIds.Contains(e.SomeValue)))
    .ToListAsync();

wertzui avatar May 12 '17 14:05 wertzui

Discussed this in triage and decided it doesn't meet the bar for a patch because:

  • It is not a regression
  • Including null in the contains list does not seem common
  • The number of customers reporting this is low despite the behavior being present for some time
  • It's fixed in 2.0, which is released

ajcvickers avatar Aug 14 '17 20:08 ajcvickers