win7user10 / Laraue.EfCoreTriggers

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

Simple After Update Trigger #23

Closed tuggernuts closed 3 years ago

tuggernuts commented 3 years ago

Hi, I am having a very difficult time understanding how to create a simple 'after update' trigger using your library. I am using MS SQL.

I need to script triggers to update columns with SQL built-in functions, e.g.:

`CREATE TRIGGER [dbo].[MyEntityTable_UPDATE] ON [dbo].[MyEntityTable] AFTER UPDATE AS BEGIN SET NOCOUNT ON;

IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN; --optional

DECLARE @Id INT

SELECT @Id = INSERTED.Id
FROM INSERTED

UPDATE dbo.MyTable
SET ModifiedDate = SYSUTCDATETIME(),
    LoggedInUser = SUSER_NAME()
WHERE Id = @Id

END`

What is the correct way to use your library to do this? Thank you.

edit: I should also mention, the entity properties ModifiedDate and LoggedInUser are read-only, since the data is generated in the database.

win7user10 commented 3 years ago

Hi, the library was designed to do simple inserting/deleting/updating based on keys of triggered entities. In your case, I can only suggest to try a raw SQL action like

modelBuilder.Entity<MyTable>()
    .AfterUpdate(trigger => trigger
        .Action(action => action
            .ExecuteRawSql(@"IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
UPDATE dbo.MyTable
SET ModifiedDate = SYSUTCDATETIME(), LoggedInUser = SUSER_NAME()
WHERE Id = {0}"), (entityBeforeUpdate, entityAfterUpdate) => entityAfterUpdate.Id)));
tuggernuts commented 3 years ago

Oh, ok, I misunderstood the description of the library. Thank you for your suggestion.