Repository navigation
Description
I'm trying to use HasDbFunction and HasTranslation to make use of the SQL AT TIME ZONE clause.
I have the following in OnModelCreating:
var methodInfo = typeof(Extensions).GetMethod(nameof(Extensions.ToTimeZone));
static string DelimitIdentifier(string identifier) => $"[{identifier.Replace("]", "]]")}]";
modelBuilder
.HasDbFunction(methodInfo)
.HasTranslation(x =>
{
var columnExpression = x.First() as ColumnExpression;
var timeZoneExpression = x.Skip(1).First() as SqlConstantExpression;
var columnIdentifier = $"{DelimitIdentifier(columnExpression.Table.Alias)}.{DelimitIdentifier(columnExpression.Name)}";
var expression = new SqlFragmentExpression($"{columnIdentifier} AT TIME ZONE {timeZoneExpression.TypeMapping.GenerateSqlLiteral(timeZoneExpression.Value)}");
Console.WriteLine($"Translation => {expression.Sql}");
return expression;
});Which is intended to translate calls to the following extension method:
public static DateTimeOffset ToTimeZone(this DateTimeOffset value, string name)
=> throw new NotImplementedException("This should be implemented in HasDbFunction.");If I try to query using this extension method like this:
var foos = from f in context.Foos
select new
{
Created = f.Created.ToTimeZone("E. Australia Standard Time")
};Instead of the ToTimeZone method being translated, the method itself seems to be called and I get the following exception:
Unhandled exception. System.NotImplementedException: This should be implemented in HasDbFunction.
MRE.EFCore5.HasDbFunction.Extensions.ToTimeZone(System.DateTimeOffset, string) in Extensions.cs
Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<T>.Enumerator.MoveNext() in SingleQueryingEnumerable.cs
MRE.EFCore5.HasDbFunction.Program.Main(string[]) in Program.cs
Even though the call to ToTimeZone isn't translated, the translation itself is being called (twice) and is generating the correct SQL fragment, however, the fragment is not included in the query and the exception from the extension method is thrown.
There is a minimal reproducible example here.
Technical Details
EF Core version: 5.0.10
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 5.0
Operating system: Windows 10
IDE: Visual Studio 2019 16.11.3
Activity
ajcvickers commentedon Sep 29, 2021
/cc @maumar
maumar commentedon Sep 30, 2021
Problem here is with using
SqlFragmentExpression- it's supposed to represent a SQL token, not an arbitrary sql statement. As such, it doesn't have a way to specify type or type mapping. We retrieve the translation from metadata, but don't apply default type mapping either (if we could, we would have applied string mapping which is default for sql fragment and that is wrong in this case anyway), so the expression is marked as not-translatable and falls back to client eval.Note to triage: As a solution, we could extend the usage of
SqlFragmentExpression, or create new expression that could represent such construct (similar to https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/blob/master/src/EFCore.MySql/Query/Expressions/Internal/MySqlComplexFunctionArgumentExpression.cs). I actually thought we already have something like this.roji commentedon Sep 30, 2021
We may simply want to add an AtTimeZone SqlExpression, and it may even make sense in relational (IIRC it's part of the SQL standard, and at least PG supports it too). This could be used in translating DateTime.ToUniversalTime and similar.
omfgicbf commentedon Oct 1, 2021
@maumar, thanks, that explains why it wasn't working.
Is there any documentation on which expressions are supported in
HasTranslation?All I could find was here and here, however, neither seems to indicate that
SqlFragmentExpressionis not supported and the silent fall-back can be a bit confusing.Am I right in thinking that solving this using my own custom expression (subclassing
SqlExpression) used to be supported but is no longer possible because ofSqlNullabilityProcessor?I came up with two workarounds; one involves wrapping
AT TIME ZONEin a user-defined function and calling it withSqlFunctionExpression, the other is wrapping the call in a "no-op" likeIIF(1 = 1, ...:Both seem to work, but I'm unsure what the impact on performance (if any) will be. I'd appreciate any suggestions on a different way to approach this.
@roji, I agree having an
AtTimeZonemethod would be good, perhaps as a part ofEF.Functions, however, there may still be other clauses that fall in the same boat (OUTPUT,READTEXT, etc, though I concede these are poor examples).[-]HasDbFunction and HasTranslation not working as expected[/-][+]Add support for AT TIME ZONE[/+]roji commentedon Oct 1, 2021
Not really - HasDbFunction is mostly used to map CLR functions to a simple SQL function call, it's rather rare for users to have to map to other SQL expression types. The relational (database-independent) SQL expressions can be found here, while the SQL Server-specific ones go here (though we currently have very few).
Note that SqlFragmentExpression is supported, just not for this kind of usage (which requires a type mapping). We can add docs for this, though this seems like a very rare edge case.
No - you are free to replace the SqlNullabilityProcessor and add support for your custom expressions. However, creating your own SQL expression type is complex and goes beyond just implementing support in SqlNullabilityProcessor; it's simply not something that users are supposed to do, only providers (it has always been this way). See the recent discussion in #26147 for more on this (especially this comment by @smitpatel).
Your workarounds may very well work OK - I'd need to see actual SQL to comment on the performance. But the right way to fix this is for us to add AT TIME ZONE support in EF Core, either in the SQL Server provider or in relational.
I don't think these are very similar... Both simply modify the statement they're in and wouldn't require a type mapping (they're more similar to query hints in this sense).
smitpatel commentedon Oct 1, 2021
I don't think "AT TIME ZONE" belongs to relational layer.
roji commentedon Oct 1, 2021
@smitpatel
AT TIME ZONEexists in SQL Server, PostgreSQL and Oracle, and might also exist in the same way in MySQL.The point here was less whether this belongs in relational or not, and more to introduce it (could be a provider-specific expression). We should also consider an EF.Functions.AtTimeZone, again either in relational or provider-specific.
omfgicbf commentedon Oct 3, 2021
@roji, thanks for the feedback.
Right, it's just that the document here refers to "Mapping a method to a custom SQL" and uses the following example:
Which isn't so simple, and implies support of more complex SQL where specific use-cases haven't been covered by other expressions.
I accept that the example given can be expressed as an expression tree, however, given my use-case doesn't seem possible to do with the provided SQL expression types, a first guess might be that
SqlFragementExpressionis the way to go.In this case, the use of "fragment" rather than "token" causes confusion around its intent, in the absence of documentation suggesting otherwise.
Right, but I can't return one from
HasTranslation, even though it inherits fromSqlExpression, as all it does is silently fail. Whereas I can construct anSqlFunctionExpression,SqlBinaryExpression, etc, and they will work, except none of them supports this use-case.The solutions I found online suggested that prior to
SqlNullabilityProcessorI could subclassSqlExpressionand resolve this, without having to replaceSqlNullabilityProcessor, which is, as you point out, not recommended.If replacing
SqlNullabilityProcessoris recommended only for providers, what is the recommended (end-user) way to support arbitrary SQL when none of the provided expressions supports it?Using the
IIFworkaround, I end up with:I agree that they were bad examples; it seems (for now) that
AT TIME ZONEis the only clause that might appear in the select list. However, was there a way to do this withHasTranslation, we needn't be dependant on the introduction ofAtTimeZone, or for whatever other use-cases that might turn up in the future.roji commentedon Oct 3, 2021
That's true, but complex SQL is very different from implementing custom expressions. Users can translate to arbitrary complex SQL constructs, as long as their basic building blocks (the expression types) are supported by the provider.
SqlFragmentExpression simply isn't like these other expressions, and wasn't meant for doing this kind of thing. I'm not sure "token" describes it better than "fragment", but that's a naming decision that is not longer very relevant.
Some notes to put this in context:
@smitpatel can confirm, but the way I see it, there's no recommended way for end users to do function translation to SQL with unsupported expression types. Either use raw SQL queries or wait for the expression to be implemented on the EF Core side (which is what I think this issue should be about).
18 remaining items
Add AtTimeZoneExpression and some relevant translations (#26972)
alrz commentedon Jan 11, 2025
Is there a proposal to support timezone at column level? e.g.
HasTimeZoneor similar. That way, no matter what datetime is passed to the query, ef could generate an appropriate query based on the timezone of the input and the one specified for the column.This is the closest issue I found to post this.
roji commentedon Jan 11, 2025
@alrz no database that I know has a dedicated time zone type, nor does one seem necessary... What's the problem with simply storing time zones as string columns?
alrz commentedon Jan 11, 2025
I mean this as an efcore feature where a datetime column is mapped with a timezone, indicating the "implicit" offset of the stored data. As a result
.Where(x=>x.DateTimeProp > value)would convert the value to the column tz before sending it out to the database.roji commentedon Jan 12, 2025
@alrz if I understood your proposal correctly, that would mean some sort of implied relationship between the column mapped to DateTimeProp and another column which represents the time zone - this is not the kind of thing that EF does (or IMHO should do). For one thing, it's unclear what happens when there's more than one DateTime (or time zone) property on the same entity type; for another, it means that the SQL translation departs very significantly from its source LINQ expression (
.Where(x=>x.DateTimeProp > value)), by implicitly including another column that isn't there in the LINQ query.All that seems unnecessary, as you can already simply have an additional string property, and then use the appropriate standard .NET function to express the time zone conversion that you wish, explicitly referencing the time zone column etc.
alrz commentedon Jan 12, 2025
That's true except for the last part. It's about the mappings of a single column.
I experimented a bit with AtTimeZone and it seems it would be sufficient. So the mapping would look like this:
This will always fetch CreatedAt with AT TIME ZONE.
Is there a way to do this today using
EF.Functions.AtTimeZone?alrz commentedon Jan 12, 2025
Seems like this incurs a perf penalty accourding to https://www.sqlskills.com/blogs/jonathan/at-time-zone-performance-issues/
If that's the case it's probably not suitable as a global config.
stevendarby commentedon Jan 12, 2025
If the column has a fixed time zone, can't you just store the datetime/offset in that time zone?
Alternatively, create a computed column which does AT TIME ZONE with the fixed time zone, add that to the model and use that in queries.
roji commentedon Jan 12, 2025
I agree with @stevendarby... The interesting case is where time zones actually vary across rows, and so an additional time zone column is needed. If the time zone is the same across all rows, then other solutions are already available which are much simpler than asking EF to tack on a static AT TIME ZONE at every point where the column is referenced...