linq2db / linq2db.EntityFrameworkCore

Bring power of Linq To DB to Entity Framework Core projects
MIT License
462 stars 38 forks source link

Using CTE with EFCore db context query? #377

Closed boomgetchopped closed 7 months ago

boomgetchopped commented 7 months ago

Hello, I want to use the below CTE in my efcore queries:

var datesCTE = dc.GetCte<DateRange>(dateHierarchy =>
{
    return
            (
                    dc.SelectQuery(() => new DateRange
                    {
                        Start = EF.Functions.DateFromParts(DateTime.Now.Year - 8, DateTime.Now.Month, 1),
                        End = EF.Functions.DateFromParts(DateTime.Now.Year - 8, DateTime.Now.Month, 1).AddMonths(1),
                    })
            )
            .Concat
            (

                from eh in dateHierarchy
                where eh.Start <= EF.Functions.DateFromParts(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
                select new DateRange
                {
                    Start = eh.End,
                    End = EF.Functions.DateFromParts(eh.End.Year, eh.End.Month, 1).AddMonths(1)
                }
            );
});

But when I join it into my query, I get a runtime error:

var innerQuery2 = 
    (from i in innerQuery.ToLinqToDB()
    from dates in datesCTE.InnerJoin(dt => (
            (dt.Start >= i.DeliveryDate && dt.Start <= (i.StopRentFinal ?? DateTime.Now))
            || (dt.End.AddDays(-1) >= i.DeliveryDate && dt.End.AddDays(-1) <= (i.StopRentFinal ?? DateTime.Now))
            || (i.DeliveryDate >= dt.Start && i.DeliveryDate >= dt.End.AddDays(-1))
        ))
    select new
    {
    ....my select list
    });

I think the issue is that my CTE is a "LinqToDB" object where my inner query is created using my EfCore DbContext.

I know the linq2db library has it's own context definitions but I just want to reuse my EfCore db context. Which I've been able to do successfully. Except for now, where I want to use this CTE in my query. And it's not working.

Error below:

variable '<>h__TransparentIdentifier0' of type DateRange]' referenced from scope '', but it is not defined