C
C#8mo ago
UltraWelfare

❔ Method either receive a disposable [context] or use a new one (EFCore - Blazor)

I'm in a blazor project where I wanna reuse some query functions. Basically sometimes I either 1. Wanna use the method on itself where it should create and dispose a new context created by the contextFactory. 2. Wanna use the method inside another method that already has a context, and just wanna pass it so it doesn't create an unneccesary one. What I currently thought of is this:
public async Task<Order?> GetOrderByUid(string uid, DbContext? context)
{
var db = context ?? await _contextFactory.CreateDbContextAsync();
var order = await db.Orders
... Other Stuff ...
.SingleOrDefaultAsync(o => o.Uid == uid);
if (context is null) await db.DisposeAsync();
return order;
}
public async Task<Order?> GetOrderByUid(string uid, DbContext? context)
{
var db = context ?? await _contextFactory.CreateDbContextAsync();
var order = await db.Orders
... Other Stuff ...
.SingleOrDefaultAsync(o => o.Uid == uid);
if (context is null) await db.DisposeAsync();
return order;
}
However I do not like the idea of manually disposing when a context is not passed. Are there any other ideas on how to approach this?
2 Replies
UltraWelfare
UltraWelfare8mo ago
Instead of dealing with the context, another idea is splitting entirely the query on itself to only mess around with IQueryables so it can be reused: Could also be an extension method
private Task<Order?> QueryOrderByUid(IQueryable<Order> query, string uid) =>
query
... Other Stuff ...
.SingleOrDefaultAsync(o => o.Uid == uid);



public async Task<Order?> GetOrderByUid(string uid)
{
await using var db = await _contextFactory.CreateDbContextAsync();
return await QueryOrderByUid(db.Orders, uid);
}
private Task<Order?> QueryOrderByUid(IQueryable<Order> query, string uid) =>
query
... Other Stuff ...
.SingleOrDefaultAsync(o => o.Uid == uid);



public async Task<Order?> GetOrderByUid(string uid)
{
await using var db = await _contextFactory.CreateDbContextAsync();
return await QueryOrderByUid(db.Orders, uid);
}
Accord
Accord8mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.