Can I share a List<T> property across multiple queries via a tracking DbContext?

39 Views Asked by At

Will the following work? And if so, will it provide a significant performance improvement.

My AppUser object includes:

public class AppUser 
{
    public int Id { get; private set; }
    // lots of other properties
    public List<Tag>? Tags { get; set; }
}

The total number of tags is presently 22 and is unlikely to grow beyond 200. So I read all of them in and cache them for any call where I need the tag(s).

Would it work to have a singleton service that creates a DbContext on first use and keeps that DbContext for the life of my application. And this is a DbContext with tracking on. And on startup it reads in all the tags. As follows:

async Task Startup() {
    dbContext = await TrackingDbFactory.CreateDbContextAsync();
    tags = await dbContext.Tags.ToListAsync();
}

Then when I need to read in an AppUser, I do:

async Task<AppUser?> GetUserAsync(int id){
    return await dbConect.Include(u => u.Tags).FirstOrDefaultAsync(u => u.Id == id);
}

In the above case, will it re-read the AppUser.Tasks from the database? Or will the DbContext use the tags list it read in earlier and re-use those already read in objects?

I do know it will need to read the AppUserTags join table. But not also reading the Tags table again would be a performance improvement. And I have 3 other list properties I would do this for, so the total performance savings would be decent.

This seems to work, but I don’t know Entity Framework well enough to test this thoroughly. So, will this work consistently, not re-reading the Tags table?

0

There are 0 best solutions below