Code: Select all
Program.cs
Code: Select all
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory();
}
< /code>
OrderService.cs
Code: Select all
private readonly IDbContextFactory _contextFactory;
public OrderService(IDbContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
public async Task GetAllOrders()
{
using var ctx = _contextFactory.CreateDbContext();
return await _context.Orders.Include(o=>o.OrderLines).ToArrayAsync();
}
< /code>
But the [url=viewtopic.php?t=15738]problem[/url] with this, is the DbContext
Code: Select all
@inject OrderService _orderSerivce;
void DoTest()
{
var orders =_orderSerivce.GetAllOrders(); // Gets 500 orders
Random r = new Random();
// edit upto 20 orders.
for(int i = 0; i < 20; i++)
{
int rInt = r.Next(0, orders.Length-1);
orders[rInt].CustomerName = "NameChanged " + i;
}
_orderSerivce.UpdateOrders(orders); // ?? What should this do
}
< /code>
I'm not sure how the UpdateOrders
public async Task UpdateOrders(Order[] orders)
{
// Use a new context instance to perform the updates
using var ctx = _contextFactory.CreateDbContext();
foreach (var order in orders)
{
// Attach each order to the context and mark it as modified
ctx.Orders.Attach(order);
ctx.Entry(order).State = EntityState.Modified;
}
// Save all changes to the database
await ctx.SaveChangesAsync();
}
< /code>
But with the disposed context, how do I now extract only the changes to update?