EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

example for inserted trigger doesn't work with multiple rows

Open jeremysimmons opened this issue 4 years ago • 2 comments

The example CREATE TRIGGER [dbo].[Blogs_UPDATE] ON [dbo].[Blogs] only deals with a single row. It does not work with all rows in the virtual INSERTED table

Something like this will work for ALL updated rows.

CREATE TRIGGER [dbo].[Blogs_UPDATE] ON [dbo].[Blogs]
    AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

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

    UPDATE dbo.Blogs
    SET LastUpdated = GETDATE()
    FROM dbo.Blogs
    JOIN INSERTED on Blogs.BlogId = INSERTED.BlogId
END

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

jeremysimmons avatar Mar 10 '21 15:03 jeremysimmons

@jeremysimmons To clarify, are you saying that the trigger as currently defined does not work with some EF Core scenario? If so, can you provide more details?

Or are you saying that the trigger would be more robust when used with non-EF Core scenario if implemented in the way you show?

ajcvickers avatar Mar 16 '21 18:03 ajcvickers

@ajcvickers sorry I didn't see this before.

are you saying that the trigger as currently defined does not work with some EF Core scenario

yes, the core scenario it doesn't work for is all rows in a multi-row insert.

can you provide more details

INSERT INTO table_name (column_list)
VALUES
    (value_list_1),
    (value_list_2),
    ...
    (value_list_n);

I suppose this isn't an issue if you're using the DbSet<T> api to add one row at a time. It's more of an issue with the database consistency in general. I think that offering a solution that will work with EF Core, but not SQL is sub-optimal. Just offer the one solution that works for both use-cases.

are you saying that the trigger would be more robust when used with non-EF Core scenario if implemented in the way you show

Yes. Suggestion is to offer a code example that works for the database holistically (my example), or at least add a disclaimer that it won't work for multi-row inserts.

jeremysimmons avatar Jul 07 '21 17:07 jeremysimmons