Skip to content

SQL Server: Support INSTEAD OF INSERT triggers #35535

Description

@sam-wheat

Question

Client of mine has INSTEAD OF INSERT trigger defined on one of their tables. This causes EF to fail when inserting rows:

The instance of entity type 'ThisEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

I have seen this documentation.
The table is defined with .HasTrigger(...), which appears to have no effect. Using UseSqlOutputClause(false) also has no effect.
Have seen this issue also.
The trigger sets SET NOCOUNT ON and does not return anything.
Removing the trigger fixes the problem but the client does not want to do that.
Anything else I can try?

SQL being run:

SET NOCOUNT ON;
INSERT INTO [TableName] (C1, C2)
VALUES (@P0, @P1);
SELECT [ID] FROM [TableName] WHERE @@ROWCOUNT = 1 AND [ID] == scope_identity();

The SELECT statement returns no rows, presumably because scope_identity is lost when the trigger returns.

.net 9
EF version 9.0.1

Your code

Stack traces


Verbose output


EF Core version

9.0.1

Database provider

No response

Target framework

No response

Operating system

No response

IDE

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions