How many times is each trigger called? #186
-
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. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The |
Beta Was this translation helpful? Give feedback.
The
SoftDeleteTrigger
causes 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.