win7user10 / Laraue.EfCoreTriggers

Library to write triggers in C# with EF.Core
MIT License
114 stars 22 forks source link

Duplicate cursor names when using multiple triggers #52

Closed kolkinn closed 2 years ago

kolkinn commented 2 years ago

Hi. I have two triggers on an entity, one AfterInsert(t => t.Action(a => a.Update(...))) and one AfterUpdate(t => t.Action(a => a.Update(...))). These both get the same cursor name Inserted<ENTITY_NAME>Cursor. This causes an error when I try to insert a row to the table:

A cursor with the same name 'InsertedMyEntityCursor' already exists.

Am I doing something wrong, or should each trigger instead be gettting their own uniquely named cursor?

My simple scenario here is setting a CreatedDate after insert and ModifiedDate after update.

Xriuk commented 2 years ago

Apparently there's an option to make the cursor local, because now it seems global: https://stackoverflow.com/a/3524875/2672235

I managed to fix that by creating a class cloned from SqlServerTriggerVisitor and changing the cursor declaration to

return $"DECLARE {cursorName} CURSOR LOCAL FOR";

then in the DbContext I replaced the service with mine:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseSqlServer(@"...").UseSqlServerTriggers(services => services.AddScoped<ITriggerVisitor, SqlServerTriggerVisitorFix>());
}

And it seems to work

kolkinn commented 2 years ago

Thank you for the workaround, @Xriuk! It worked very well.