How many times is each trigger called? #186
Answered
by
koenbeuk
shinmendokkodo
asked this question in
Q&A
public class LoadCascadingEntitiesTrigger : IBeforeSaveTrigger<IEntity>, ITriggerPriority
{
readonly RepositoryContext repositoryContext;
public LoadCascadingEntitiesTrigger(RepositoryContext repositoryContext)
{
this.repositoryContext = repositoryContext;
}
public int Priority => -1;
public Task BeforeSave(ITriggerContext<IEntity> context, CancellationToken cancellationToken)
{
if (context.ChangeType is ChangeType.Deleted)
{
var entry = repositoryContext.Entry(context.Entity);
foreach (var navigationMetadata in entry.Metadata.GetNavigations())
{
if (navigationMetadata.ForeignKey.DeleteBehavior == DeleteBehavior.Cascade)
{
var navigation = entry.Navigation(navigationMetadata!.PropertyInfo!.Name);
if (!navigation.IsLoaded)
{
navigation.Load();
}
}
}
repositoryContext.ChangeTracker.CascadeChanges();
}
return Task.CompletedTask;
}
}
using Entities;
using EntityFrameworkCore.Triggered;
using Microsoft.EntityFrameworkCore;
namespace Repository.Triggers
{
public class SoftDeleteTrigger : IBeforeSaveTrigger<IEntity>, ITriggerPriority
{
readonly RepositoryContext repositoryContext;
public SoftDeleteTrigger(RepositoryContext repositoryContext)
{
this.repositoryContext = repositoryContext;
}
public int Priority => 0;
public Task BeforeSave(ITriggerContext<IEntity> context, CancellationToken cancellationToken)
{
if (context.ChangeType is ChangeType.Deleted)
{
context.Entity.IsDeleted = true;
repositoryContext.Entry(context.Entity).State = EntityState.Modified;
}
return Task.CompletedTask;
}
}
}Hi, If you could please tell me is this expected or something is wrong in my configuration, I'll be really grateful. Below is my configuration public static IServiceCollection ConfigureDbContext(this IServiceCollection services, IConfiguration configuration)
{
return services.AddDbContext<RepositoryContext>(opt =>
{
opt.UseSqlServer(configuration.GetConnectionString("sqlConnection"));
opt.UseTriggers(trigOpt =>
{
trigOpt.AddTrigger<LoadCascadingEntitiesTrigger>();
trigOpt.AddTrigger<SoftDeleteTrigger>();
});
});
}Thanks. |
Answered by
koenbeuk
Sep 29, 2023
Replies: 1 comment 1 reply
|
The |
1 reply
Answer selected by
shinmendokkodo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
SoftDeleteTriggercauses the entity to be marked as modified instead of Deleted. This subsequently causes triggers to fire again as now something different happened. This is by design.