Skip to content

Get latest version of all from temporal table, with include. #34384

Closed as not planned

Description

@AllanMichaelsen

I was playing around with temporal tables and it is great in so many ways such as traceability and "blaming" ;-)

But... I hit a wall when it came to getting the latest version of all using TemporalAll(). I did the grouping, got the latest version according to timestamps and that's great, but then in real life code where I'm using Include() it falls apart.

Now I've read a lot of posts and ideas and what not, but none of them hits the mark I'm aiming for. So, the question is this: Is there a way of getting all the latest versions of entities (active and/or historic) while maintaining the ability to join other tables using Include()?

I was trying to get data using an IQueryable so I can build on my query with input parameters.

public static IQueryable<T> GetQueryable<T>(this Context context, Expression<Func<T, bool>>? query = null, List<string>? includes = null, bool includeActive = true, bool includeDeleted = false, Expression<Func<T, object>>? orderBy = null, bool orderDescending = false)
{
    if (!includeActive && !includeDeleted)
    {
        return new List<T>().AsQueryable();
    }

    IQueryable<T> queryable = context
            .Set<T>()
            .TemporalAll()
            .GroupBy(x => x.Id)
            .Select(x => x
                .OrderByDescending(g => EF.Property<DateTime>(g, "PeriodEnd"))
                .First());

    if (includeActive && !includeDeleted)
    {
        queryable = queryable.Where(x => x.UpdateStatus != UpdateStatusEnum.Deleted);
    }
    else if (!includeActive && includeDeleted)
    {
        queryable = queryable.Where(x => x.UpdateStatus == UpdateStatusEnum.Deleted);
    }

    if (orderBy is not null)
    {
        queryable = orderDescending
            ? queryable.OrderByDescending(orderBy)
            : queryable.OrderBy(orderBy);
    }

    if (includes is not null && includes.Count > 0)
    {
        queryable = includes.Aggregate(queryable, (current, include) => current.Include(include));
    }

    if (query is not null)
    {
        queryable = queryable.Where(query);
    }

    return queryable;
}

So as you can see I ran into issues with the Include(), but even when I tried removing it and just get the additional data through secondary calls, it still crashed because I also use AutoMapper and .Project(), which in turn has the same issue as it uses Include() to get additional data.

I was wondering if there is a way of getting all the latest versions on historic entities using AsOf() and that way being able to use Include()?

Include provider and version information

EF Core version: 8.0.7
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0
Operating system: Win 11 Pro
IDE: Visual Studio 2022 17.11

Activity

  1. maumar commented on Aug 9, 2024

    @maumar
    Contributor

    There is no way to use temporal table feature with include or any form of navigation access if you are using temporal option other than AsOf. Reason is that we quickly run into trouble with bucketing the results. e.g. consider the following:

            using (var ctx = new MyContext())
            {
                await ctx.Database.EnsureDeletedAsync();
                await ctx.Database.EnsureCreatedAsync();
    
                var p1 = new Post { Title = "p1" };
                var b1 = new Blog { Name = "b1", Posts = new List<Post> { p1 } };
    
                ctx.Blogs.Add(b1);
                await ctx.SaveChangesAsync();
    
                await Task.Delay(5000);
    
                b1.Name = "Modified b1";
                await ctx.SaveChangesAsync();
    
                await Task.Delay(5000);
    
                var p2 = new Post { Title = "p2" };
                b1.Posts.Add(p2);
                await ctx.SaveChangesAsync();
            }
    

    create a blog with one post, then modify the blog, then add post

    when doing ctx.Blogs.TemporalAll().Include(x => x.Posts).ToListAsync();

    I would probably expect to get one result for "b1" blog with "p1" post, then "modified b1" with "p1" and then "modified b1"
    with "p1" and "p2"

    But we would try to naively translate the query to:

    SELECT [b].[Id], [b].[Name], [b].[PeriodEnd], [b].[PeriodStart], [p].[Id], [p].[BlogId], [p].[PeriodEnd], [p].[PeriodStart], [p].[Title]
    FROM [Blogs] FOR SYSTEM_TIME ALL AS [b]
    LEFT JOIN [Posts] FOR SYSTEM_TIME ALL AS [p] ON [b].[Id] = [p].[BlogId]
    ORDER BY [b].[Id]
    

    which returns 4 rows (b1 + p1, b1 + p2, modified b1 + p1 and modified b1 + p2) (each table returning all of it's historical elements, irrespective or relationship between them). It's just too hard to make this work.

    What you could try is to extract period ends for all the ids, and then in another set of queries use AsOf with those extracted periods. Something like this?

    var latestRoots = await context
                .Set<T>()
                .TemporalAll()
                .GroupBy(x => x.Id)
                .Select(x => x
                    .OrderByDescending(g => EF.Property<DateTime>(g, "PeriodEnd").Select(g => new { Period = EF.Property<DateTime>(g, "PeriodEnd"), Id = g.Id}).First()).ToListAsync();

    and then

    foreach (var foo in latestRoots)
    {
    var query = await context.Set<T>().TemporalAsOf(foo.Period).Where(x => x.Id == foo.Id).Include(...).ToListAsync();
    }

    but this involved n+1 queries so its not a great.

  2. AllanMichaelsen commented on Aug 11, 2024

    @AllanMichaelsen
    Author

    I actually tried that already and of course it works, but as you say... Results in n+1...

    So there is no other way and nothing in the plans? Like using your example, but before joining anything, returning just the last item like in my example and the allowing join to that?
    Making it a specific method ie. "TemporalGetLatest()"?

  3. assigned and unassigned on Sep 12, 2024
  4. maumar commented on Oct 31, 2024

    @maumar
    Contributor

    We don't have anything planned from EF. The recommendation is for people to hand-craft the queries using joins. I filed a documentation issue to provide some guidance on how it can be done. The "get latest" case is tricky because currently composing Join / SelectMany on top of this shape fails due to shortcomings in our group by translation. So for EF 8-9 the only way to do it realistically is N+1. We hope to improve the group by translation for EF 10. If we manage to do it, you can improve the performance of the query by composing join to the groupby-select-orderbydesceding pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions