score:1

so in the end i've managed to get a preliminary solution based on jeremy's solution. it does the trick but must be improved a lot. currently it only works if expected datetime to be converted is a column of a table (but can be extended to constants or parameters).

this is the part that implements the extensions methods and register them on the context's modelbuilder as dbfunctions during the onmodelcreating event:

public static partial class customdbfunctions
{
    public static datetime? totimezone(this datetime? source, string timezone)
    {
        if (!source.hasvalue) return null;
        return datetimehelper.utcdatetolocal(source.value, timezone);
    }

    public static datetime totimezone(this datetime source, string timezone)
    {
        return totimezone((datetime?)source, timezone).value;
    }

    public static modelbuilder addcustomfunctions(this modelbuilder builder)
    {
        builder.hasdbfunction(typeof(customdbfunctions).getmethod(nameof(totimezone), new[] { typeof(datetime), typeof(string) }))
            .hastranslation(args =>
            {
                var datetimeexpression = args.elementat(0);
                if (datetimeexpression is columnexpression column) 
                {
                    return new timezonecolumnexpression(column.name, column.property, column.table, args.elementat(1));
                }
                return datetimeexpression;
            });
        builder.hasdbfunction(typeof(customdbfunctions).getmethod(nameof(totimezone), new[] { typeof(datetime?), typeof(string) }))
            .hastranslation(args =>
            {
                var datetimeexpression = args.elementat(0);
                if (datetimeexpression is columnexpression column)
                {
                    return new timezonecolumnexpression(column.name, column.property, column.table, args.elementat(1));
                }
                return datetimeexpression;
            });
        return builder;
    }
}

and this is the custom expression derived from microsoft.entityframeworkcore.query.expressions.columnexpression. it only intercepts the querysqlgenerator in order to add some sql fragments:

public class timezonecolumnexpression : columnexpression
{
    private readonly expression timezoneid;

    public timezonecolumnexpression(string name, iproperty property, tableexpressionbase tableexpression, expression timezoneid) : base(name, property, tableexpression)
    {
        this.timezoneid = timezoneid ?? throw new argumentnullexception(nameof(timezoneid));
    }

    protected override expression accept(expressionvisitor visitor)
    {
        if (!(visitor is iquerysqlgenerator))
            return base.accept(visitor);

        visitor.visit(new sqlfragmentexpression("convert(datetime2, "));
        base.accept(visitor);
        visitor.visit(new sqlfragmentexpression($" at time zone 'utc' at time zone "));
        visitor.visit(timezoneid);
        visitor.visit(new sqlfragmentexpression(")"));
        return this;
    }
}

use:

            var timezone = timezoneinfo.findsystemtimezonebyid(timezoneconverter.tzconvert.ianatowindows("europe/madrid"));
            var groups = await repository.asqueryable<user>().where(x => x.id > 0)
                .groupby(x => new { x.begindateutc.totimezone(timezone.id).date })
                .select(x => 
                new 
                {
                    date = x.key,
                    count = x.count()
                }).tolistasync();

output:

info: microsoft.entityframeworkcore.database.command[20101]
      executed dbcommand (80ms) [parameters=[@__timezone_id_0='romance standard time' (size = 4000)], commandtype='text', commandtimeout='120']
      select convert(date, convert(datetime2, [x].[begindateutc] at time zone 'utc' at time zone @__timezone_id_0)) as [date], count(*) as [count]
      from [dbo].[users] as [x]
      where [x].[id] > cast(0 as bigint)
      group by convert(date, convert(datetime2, [x].[begindateutc] at time zone 'utc' at time zone @__timezone_id_0))

score:1

in ef core 5

in ef core 5 the below code worked for me: function definition

public static class queryhelper
{
    public static datetimeoffset? totimezone(this datetime? source, string timezone)
    {
        if (!source.hasvalue) return null;
        var tz = timezoneinfo.findsystemtimezonebyid(timezone);
        var date = timezoneinfo.converttimefromutc(source.value, tz);
        return new datetimeoffset(date, tz.getutcoffset(date));
    }
    public static datetimeoffset totimezone(this datetime source, string timezone)
    {
        return attimezonesql((datetime?)source, timezone).value;
    }}

custom expression builder

        public class attimezoneexpression5 : sqlfunctionexpression
        {
            private readonly ireadonlycollection<sqlexpression> _params;

            public attimezoneexpression5(ireadonlycollection<sqlexpression> parameters) : base("notimportant", true, typeof(datetimeoffset), relationaltypemapping.nullmapping)
            {
                _params = parameters;
            }
            protected override expression accept(expressionvisitor visitor)
            {
                if (!(visitor is querysqlgenerator))
                    return base.accept(visitor);
                if (_params.first().typemapping.dbtype == system.data.dbtype.date)
                    visitor.visit(new sqlfragmentexpression("convert(datetime2, "));
                visitor.visit(_params.first());                         //first paramenter
                if (_params.first().typemapping.dbtype == system.data.dbtype.date)
                    visitor.visit(new sqlfragmentexpression(")"));
                visitor.visit(new sqlfragmentexpression(" at time zone "));
                visitor.visit(_params.skip(1).first());                 //2nd parameter
                return this;
            }
            protected override void print([notnullattribute] expressionprinter expressionprinter)
            {
                console.writeline(expressionprinter);
            }
        }

then in on model creating we should use

      builder.hasdbfunction(typeof(queryhelper).getmethod(nameof(totimezone), new[] { typeof(datetime), typeof(string) }))
.hastranslation(args =>
{
     return new attimezoneexpression5(args);
}
      builder.hasdbfunction(typeof(queryhelper).getmethod(nameof(totimezone), new[] { typeof(datetime?), typeof(string) }))
.hastranslation(args =>
{
     return new attimezoneexpression5(args);
}

Related Query

More Query from same tag