-
If using services.AddDbContextFactory(...) as in your BlazorTests project, how does one create a BeforeSave trigger which needs to create/add entities outside of the current ITriggereContext as in the SignupToMandatoryCourses trigger example? Is there a way to reference the underlying DbContext within the trigger rather than constructor injection? My dbcontext registration is: And my trigger is defined as: public class AddAuditTrigger : IBeforeSaveTrigger<AppUser>
{
private readonly IDbContextFactory<AppDbContext> _appDbContextFactory;
public AddAuditTrigger (
IDbContextFactory<AppDbContext> appDbContextFactory)
{
_appDbContextFactory = appDbContextFactory ?? throw new ArgumentNullException(nameof(appDbContextFactory));
}
public async Task BeforeSave(
ITriggerContext<AppUser> context,
CancellationToken cancellationToken)
{
if (context.ChangeType == ChangeType.Added)
{
var db = _appDbContextFactory.CreateDbContext(); //<-- This isn't the same context, so how to persist new entities on original SaveChanges()?
db.UserAudits.Add(new EntityChange { EntityType = "SomeEntity" });
// If I call db.SaveChanges(), it works. But if the original SaveChanges() fails, my db is left in an inconsistent state.
// Is this a job for transactions or is there an easier way?
}
}
} My triggers were working when I registered my DBContext via "services.AddDbContext(...)", but when switching to the recommended "services.AddDbContextFactory(...)" for Blazor Server I've hit a problem with the more complex triggers that write to entities outside of the current ITriggereContext. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Thanks for brining this up, this is indeed a bug in the sample. What we should have used here is Once using that, things should just work. This issue is really with EF itself where AddDbContext would resolve a DbContext with the ApplicationServiceProvider scoped to the current request whereas AddPooledDbContext or AddDbContextFactory would set the ApplicationServiceProvider to the root ServiceProvider (Which is not scoped and therefore does not share your service instances). In short, use: The EF issue is tracked over here: |
Beta Was this translation helpful? Give feedback.
-
This is now fixed on master through this PR: https://github.com/koenbeuk/EntityFrameworkCore.Triggered/pull/106/files Make sure to use services.AddTriggeredDbContextFactory as well as version 2.3.1 or up (going to release that version shortly) |
Beta Was this translation helpful? Give feedback.
This is now fixed on master through this PR: https://github.com/koenbeuk/EntityFrameworkCore.Triggered/pull/106/files
Make sure to use services.AddTriggeredDbContextFactory as well as version 2.3.1 or up (going to release that version shortly)