I have a lot of “repo” classes which load in a tables rows and then keeps them in memory, providing a way to get them without re-querying the database.
Is there a way I can get rid of this? If I inject my dbContext and query the DbSet it uses a new query every time?
LoadInitialDataAsync gets called on bootup, then I use TryGetByCodeName throughout my application when needed.
Example:
public class TabRepository(SadieContext dbContext)
{
private Dictionary<string, NavigatorTab> _tabs = new();
public async Task LoadInitialDataAsync()
{
_tabs = await dbContext.Set<NavigatorTab>()
.Include(x => x.Categories)
.ToDictionaryAsync(x => x.Name, x => x);
}
public bool TryGetByCodeName(string codeName, out NavigatorTab? tab) =>
_tabs.TryGetValue(codeName, out tab);
}
With context:
var tabs = await dbContext.Set<NavigatorTab>()
.Include(x => x.Categories)
.ToDictionaryAsync(x => x.Name, x => x)
adam says is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.