hazzik / DelegateDecompiler

A library which is able to decompile a delegate or a method body to its lambda representation
MIT License
526 stars 62 forks source link

Decompile DateTime to play with ToUniversalTime and ToLocalTime #115

Closed nawfalhasan closed 6 years ago

nawfalhasan commented 6 years ago

Say I have a DateTime property coming from DB which is in UTC. I would like to display it in local time in front-end. E.g.

public partial class Order
{
    public DateTime OrderDate { get; set; }

    [Computed]
    public DateTime OrderDateLocal => OrderDate.ToLocalTime();
}

My EF query would look like,

IQueryable query = new NORTHWNDEntities().Orders.Select(o => new { o.OrderDateLocal }).Decompile();

I would like subsequent OrderBy and Where on query to be based on OrderDateLocal.ToUniversalTime.

The advantage of ToLocalTime and ToUniversalTime are that they take care of DST conversion if any.

For e.g. my query,

var filtered = new NORTHWNDEntities().Orders.Where(x => x.OrderDateLocal == new System.DateTime(1996, 7, 4)).Decompile().ToList();

fails with

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: LINQ to Entities does not recognize the method 'System.DateTime ToLocalTime()' method, and this method cannot be translated into a store expression.

I could achieve somewhat by doing this:

public partial class Order
{
    public DateTime OrderDate { get; set; }

    [Computed]
    public DateTime OrderDateLocal => DbFunctions.AddMinutes(OrderDate, someOffSetValue);
}

but this doesn't handle DST as far as I understand.

hazzik commented 6 years ago

This is not in the scope of the DelegateDecompiler. The problem is that EF does not support these methods.