EF Core Change Tracking und Blazor ServerC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 EF Core Change Tracking und Blazor Server

Post by Anonymous »

Ich habe Mühe, ein gutes Muster für die Arbeit mit EF Core und Blazor Server zu finden. Wickeln Sie dann jede Operation in seinen eigenen dbContext .

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
wird entsorgt, und ich werde alle Änderungsverfolgungsfähigkeiten verlieren.

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
Funktion sollte funktionieren? Savechanges hätte verfolgt, was bearbeitet und was neu ist, und alles für mich umgehen. Z. B. < /p>
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?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post