Using the code you posted in your new answer. But same error when I add a file and the method UpdateVergadering
is called.
vergaderingRepository:
private readonly IDbContextFactory<ApplicationDbContext> _factory;
public VergaderingRepository(IDbContextFactory<ApplicationDbContext> dbContextFactory, IDbContextFactory<ApplicationDbContext> factory)
{
_factory = factory;
}
public async ValueTask<int> UpdateVergadering(Vergadering vergadering)
{
using var dbContext = _factory.CreateDbContext();
dbContext.Set<Vergadering>().Update(vergadering);
return await dbContext.SaveChangesAsync();
}
public async ValueTask<Vergadering> GetVergaderingVoorLiveNotulenAsync (int vergaderingId)
{
using var dbContext = _factory.CreateDbContext();
dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
return await dbContext.Set<Vergadering>().SingleOrDefaultAsync(x => x.Id == vergaderingId);
}
The error I get:
System.InvalidOperationException: ‘The instance of entity type ‘Bestuurslid’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
2
Answers
You code never completes the component render, you loop within
OnInitialized
. You also confuseOnInitialized
andOnInitializedAsync
.Here’s a demo page that shows how to use the
System.Timers.Timer
with an event handler hooked up to the timer to handle the data get and UI update.OnInitializedAsync
does the initial data get, sets up the timer, wires up the event handler and completes.Update on DbContexts and Async behaviour
Set up a DbContextFactory:
And then use the factory to get Db context instances as you need them.
DbContextFctory Update
You’ve implemented the factory, but not the "Unit of Work" pattern. You’re implementation uses the same context for all activity within the repository and will cause usage clashes.
Blazor lives in an async world so you need to code for situations where you have parallel processes running on the same resources.
Your Repository Pattern should look like this: