dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.62k stars 1.96k forks source link

example for inserted trigger doesn't work with multiple rows #3149

Open jeremysimmons opened 3 years ago

jeremysimmons commented 3 years ago

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.

ajcvickers commented 3 years ago

@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?

jeremysimmons commented 3 years ago

@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 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.