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

Bug when using DatabaseContext in Computed method #152

Closed Aleksaas closed 1 year ago

Aleksaas commented 5 years ago

I have a method like this:

        [Computed]
        public bool ForWeek(DateTime? dateFrom, DatabaseContext ctx)
        {
            return DateFrom <= dateFrom
                && ctx.ShiftPeriods.Max(s => s.DateFrom) == DateFrom;
        }

Ignore the logic, its only for testing :) But when it is compiled query looks like this:

from ShiftPeriod s in DbSet<ShiftPeriod>
select s.DateFrom).Max() == [e].DateFrom

And this is query without delegate decompiler:

from ShiftPeriod s in DbSet<ShiftPeriod>
where (Nullable<DateTime>)[s].DateFrom <= __dateFrom_3
select (Nullable<DateTime>)[s].DateFrom).Max() == (Nullable<DateTime>)[e].DateFrom

See how 's' is without '[]' in DD query, which leads to optimized query looks like:

from ShiftPeriod d in DbSet<ShiftPeriod>
where !([d].Deleted)
select s.DateFrom).Max() == [d].DateFrom

And I get error: variable 's' of type 'ShiftPeriod' referenced from scope '', but it is not defined

So I assume there is bug when DatabseContext is used inside a computed method :) Or maybe DD is not supposed to work like that and I should not use DatabseContext inside computed method?

magicmoux commented 4 years ago

Could you please provide a full sample to check this further? Thx in advance Max

cervengoc commented 3 years ago

Hi @hazzik, @magicmoux ,

We've just ran into the same issue, and I've added a failing test for it. Could you please have a look at my branch?

Br, Zoltán

magicmoux commented 3 years ago

Hi @cervengoc ,

As I suspected the problem is that DD currently handles System.Linq.Expressions.Expression.xxx methods verbatim, which finally confuses the ELinq translator.

At the time I proposed #151 to handle these calls. I just upgraded it to include the latest changes from hazzik/develop (as a hot-fix) and updated your tests for POC.

hazzik commented 1 year ago

This should be fixed by #192