Regression: GroupBy generates invalid SQL when using custom database function
I wasn't sure if to comment on the issue since it was closed, but the bug reported in #29638 is present again in 8.0.
The sample provided in that issue reproduces the bug.
var orderIds = new [] { Guid.NewGuid(), Guid.NewGuid() };
var orders = dbContext.Orders
.Where(c => dbContext.AsQueryable(orderIds).Contains(c.OrderId))
.Select(c => new
{
c.Project.Code,
c.Project.Revenue
})
.GroupBy(c => new
{
c.Code
})
.Select(c => new
{
c.Key.Code,
Sum = c.Sum(e => e.Revenue)
}).ToList();
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "s.Value" could not be bound.
Environment details: EF Core: 8.0.1 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 8.0 (Daily builds) Operating system: Windows 10 IDE: Visual Studio 2022 17.9.0 Preview 2.1
Duplicate of #32234
@cryogen can you please give the latest daily build a try? This is almost certainly already fixed for 8.0.2, and it would be good to get confirmation for your case.
@roji Can still reproduce on 9.0.0-alpha.1.24060.3
I am unable to reproduce this on my end. Trying this code:
var optionsBuilder = new DbContextOptionsBuilder<TestContext>();
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Repro32772;Trusted_Connection=True;MultipleActiveResultSets=true");
using var dbContext = new TestContext(optionsBuilder.Options);
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
var orderIds = new[] { Guid.NewGuid(), Guid.NewGuid() };
var orders = dbContext.Orders
.Where(c => dbContext.AsQueryable(orderIds).Contains(c.OrderId))
.Select(c => new
{
c.Project.Code,
c.Project.Revenue
})
.GroupBy(c => new
{
c.Code
})
.Select(c => new
{
c.Key.Code,
Sum = c.Sum(e => e.Revenue)
}).ToList();
public class Project
{
public Guid ProjectId { get; set; }
public decimal Revenue { get; set; }
public string Code { get; set; }
}
public class Order
{
public Guid OrderId { get; set; }
public Guid ProjectId { get; set; }
public Project Project { get; set; }
}
public class TestContext : DbContext
{
public TestContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ConfigureDbFunctions();
}
[Keyless]
private class StringSplitResult
{
public string Value { get; set; }
}
[DbFunction(IsBuiltIn = true, Name = "STRING_SPLIT")]
private IQueryable<StringSplitResult> Split(string source, string separator)
=> FromExpression(() => Split(source, separator));
public IQueryable<Guid> AsQueryable(IEnumerable<Guid> source)
=> Split(string.Join(",", source.Select(x => Convert.ToString(x))), ",")
.Select(s => DbFunctionExtensions.ToGuid(s.Value)!.Value);
}
public static class DbFunctionExtensions
{
public static Guid? ToGuid(string value) => throw new NotImplementedException();
public static void ConfigureDbFunctions(this ModelBuilder modelBuilder)
{
var type = typeof(DbFunctionExtensions);
modelBuilder.HasDbFunction(type.GetMethod(nameof(ToGuid))!)
.HasTranslation(t => new SqlFunctionExpression(
functionName: "CONVERT",
arguments: new[] { new SqlFragmentExpression("UNIQUEIDENTIFIER"), t[0] },
nullable: true,
argumentsPropagateNullability: new[] { false, true },
typeof(Guid),
typeMapping: null))
.IsBuiltIn();
}
}
and we generate sql with correctly uniquified aliases:
SELECT [p].[Code], (
SELECT COALESCE(SUM([p1].[Revenue]), 0.0)
FROM [Orders] AS [o0]
INNER JOIN [Projects] AS [p0] ON [o0].[ProjectId] = [p0].[ProjectId]
INNER JOIN [Projects] AS [p1] ON [o0].[ProjectId] = [p1].[ProjectId]
WHERE [o0].[OrderId] IN (
SELECT CONVERT(UNIQUEIDENTIFIER, [s0].[Value])
FROM STRING_SPLIT(@__source_1, @__separator_2) AS [s0]
) AND ([p].[Code] = [p0].[Code] OR ([p].[Code] IS NULL AND [p0].[Code] IS NULL))) AS [Sum]
FROM [Orders] AS [o]
INNER JOIN [Projects] AS [p] ON [o].[ProjectId] = [p].[ProjectId]
WHERE [o].[OrderId] IN (
SELECT CONVERT(UNIQUEIDENTIFIER, [s].[Value])
FROM STRING_SPLIT(@__source_1, @__separator_2) AS [s]
)
GROUP BY [p].[Code]
@__source_1 nvarchar(4000),
@__separator_2 nvarchar(4000)',
@__source_1=N'83241757-4c78-4f2e-97e8-77a56a295392,7f5ea5e5-52b4-45d5-bf61-d74508d391fc',
@__separator_2=N','
@cryogen are you using the same exact code and seeing different results? If so, there could be some configuration issue perhaps? If your code is different, can you please modify the code snippet I listed above so that it shows the problem?
@maumar Apologies, the example I linked to was indeed not configured correctly on my end. I included it because it was a shorter reproduction case.
However the issue still persists for my case, I've included the (slightly longer) code below.
My example uses discriminators which the one I linked to does not.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using System.Linq.Expressions;
using TimeZoneConverter;
var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlServer("Server=localhost;Database=TestDb;Trusted_Connection=True;Encrypt=False;");
using var dbContext = new DatabaseContext(optionsBuilder.Options);
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
var timeZone = "GMT Standard Time";
var foo = await dbContext.EntityA
.Where(_ => _.EntityB is EntityEnumA &&
_.Parent.ConfirmedDate >= new DateTime(2023, 1, 1) && _.Parent.ConfirmedDate < new DateTime(2024, 1, 1))
.Select(_ => new
{
_.Parent.ConfirmedDate,
SalesPriceSum = (_.EntityB as EntityEnumA).PriceBreakdown.SalesPrice
})
.GroupBy(_ => new
{
_.ConfirmedDate.FromUtcToTimeZone(timeZone).Value.Month,
_.ConfirmedDate.FromUtcToTimeZone(timeZone).Value.Year
})
.Select(_ => new
{
PeriodStartDate = new DateTime(_.Key.Year, _.Key.Month, 1),
Sum = _.Sum(i => i.SalesPriceSum)
}).ToListAsync();
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions options) : base(options)
{
}
public DbSet<ParentEntity> Parents { get; set; }
public DbSet<EntityA> EntityA { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(DatabaseContext).Assembly);
modelBuilder.HasDbFunction(typeof(DateTimeExtensions).GetMethod(nameof(DateTimeExtensions.FromUtcToTimeZone), new[] { typeof(DateTime), typeof(string) }))
.HasTranslation(args => new AtTimeZoneExpression(args));
modelBuilder.HasDbFunction(typeof(DateTimeExtensions).GetMethod(nameof(DateTimeExtensions.FromUtcToTimeZone), new[] { typeof(DateTime?), typeof(string) }))
.HasTranslation(args => new AtTimeZoneExpression(args));
}
}
public class EntityA
{
public int Id { get; set; }
public virtual EntityB EntityB { get; set; }
public virtual ParentEntity Parent { get; set; }
}
public abstract class EntityB
{
public int Id { get; set; }
public EnumType Type { get; set; }
internal class Configuration : IEntityTypeConfiguration<EntityB>
{
public void Configure(EntityTypeBuilder<EntityB> builder)
{
builder.Property(_ => _.Type)
.IsRequired();
builder.HasDiscriminator(_ => _.Type)
.HasValue<EntityEnumA>(EnumType.A)
.HasValue<EntityEnumB>(EnumType.B);
}
}
}
public class ParentEntity
{
public int Id { get; set; }
public DateTime? ConfirmedDate { get; set; }
public virtual ICollection<EntityA> Children { get; set; }
}
public class PriceBreakdown
{
public int Id { get; set; }
public decimal SalesPrice { get; set; }
}
public class EntityEnumA : EntityB
{
public virtual PriceBreakdown PriceBreakdown { get; set; }
}
public class EntityEnumB : EntityB
{
}
public enum EnumType
{
A = 1,
B = 2
}
public static class DateTimeExtensions
{
public static DateTime? FromUtcToTimeZone(this DateTime? source, string timeZoneId)
{
return source != null ? FromUtcToTimeZone(source.Value, timeZoneId) : null;
}
public static DateTime FromUtcToTimeZone(this DateTime source, string timeZoneId)
{
var timeZone = TZConvert.GetTimeZoneInfo(timeZoneId);
return TimeZoneInfo.ConvertTimeFromUtc(source, timeZone);
}
}
public class AtTimeZoneExpression : SqlFunctionExpression
{
private readonly IReadOnlyCollection<SqlExpression> _params;
public AtTimeZoneExpression(IReadOnlyCollection<SqlExpression> parameters) : base("ToLocal", true, typeof(DateTime), RelationalTypeMapping.NullMapping)
{
_params = parameters;
}
protected override Expression Accept(ExpressionVisitor visitor)
{
if (visitor is not QuerySqlGenerator)
{
return base.Accept(visitor);
}
visitor.Visit(_params.First());
visitor.Visit(new SqlFragmentExpression(" AT TIME ZONE 'UTC' AT TIME ZONE "));
visitor.Visit(_params.Skip(1).First());
return this;
}
}
@cryogen I am able to reproduce this now, thanks - will investigate.
@cryogen the problem here is that AtTimeZoneExpression stores column parameters in a private state but doesn't let our visitors process them - it calls to processing logic on the base class (SqlFunctionExpression), but that logic doesn't know anything about _params.
You can/should use EF.Functions.AtTimeZone() instead of creating SqlFunctionExpression-derived type.
@maumar Thanks. Was not aware of the existence of this new EF function. This does indeed have the functionality I need and works ok.
Interesting that our custom function used to work in version 6 though, but as I now have what I need I'll leave it up to you to close this issue or not.
As discussed in triage, closing as this was a user-side issue in the implementation of the expression type. In general, implementating a new experssion type is a highly advanced scenario that requires changes in various parts of EF (e.g. SqlNullabilityProcessor); this is something we really do not recommend, and perfer to hear about any scenario where there's a missing expression type so that we can possibly provide built-in support for it, if that makes sense.