Skip to content

UpdatedAt Table Trigger problem SQL Server #136

@gianox

Description

@gianox

Describe the bug

I have a table named AspectClasses. When I enable the trigger:

CREATE OR ALTER TRIGGER [dbo].[AspectClasses_UpdatedAt]
ON [dbo].[AspectClasses]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE
[dbo].[AspectClasses]
SET
[UpdatedAt] = GETUTCDATE()
WHERE
[Id] IN (SELECT [Id] FROM INSERTED);
END

I get the following error when using the repository method "await someRepository.ReplaceAsync(someAspectClass)"

The target table 'AspectClasses' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.

To Reproduce

Steps to reproduce the behavior:

I fetch an object using var someAspectClass = await someRepository.ReadAsync(someAspectClassId);

Change a property on someAspectClass

call the await someRepository.ReplaceAsync(someAspectClass);

Expected behavior

Modified someAspectClass is saved with an updated UpdatedAt property

What platforms?

  • Server:
    • Version of dotnet being used to compile? .NET 8.0
    • Library versions? Latest
    • What database are you using? SQL Server
    • Where are you running the server? Azure

Additional context

Add any other context about the problem here.

I tried working around the issue by doing this in my DbContext:

public override async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
await SetUpdatedAt();
return await base.SaveChangesAsync(cancellationToken);
}

private async Task SetUpdatedAt()
{
var entries = ChangeTracker.Entries().Where(e => (e.State == EntityState.Added || e.State == EntityState.Modified));

foreach (var entry in entries)
{
    var entity = (ExtEntityData)entry.Entity;

    if (entry.State == EntityState.Modified)
    {
        entity.UpdatedAt = DateTimeOffset.UtcNow;
    }
}

}

The task is finishes without issue, but the entry in the database does not get an updated UpdatedAt value.

Metadata

Metadata

Assignees

Labels

DocumentationImprovements or additions to documentation

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions