Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SQL Server: Support INSTEAD OF INSERT triggers #35535

Open
sam-wheat opened this issue Jan 27, 2025 · 3 comments
Open

SQL Server: Support INSTEAD OF INSERT triggers #35535

sam-wheat opened this issue Jan 27, 2025 · 3 comments

Comments

@sam-wheat
Copy link

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

@ErikEJ
Copy link
Contributor

ErikEJ commented Jan 27, 2025

Map Inserts to a stored procedure?

@roji
Copy link
Member

roji commented Jan 27, 2025

EF expects INSERTs (and other statements) to behave in the standard way, and triggers are indeed known to sometimes mess that up. @AndriySvyryd any known workarounds here? (the SO linked to above provides some possibilities)

@AndriySvyryd
Copy link
Member

I don't know of any straightforward workarounds for this.

EF would need to generate different SQL for different scenarios. I think we'll need to add ways to force the usage of OUTPUT INTO for single row or to use @@IDENTITY instead of scope_identity().

@AndriySvyryd AndriySvyryd added this to the Backlog milestone Jan 27, 2025
@AndriySvyryd AndriySvyryd changed the title INSERT trigger causes EF to fail when inserting SQL Server: Support INSTEAD OF INSERT triggers Jan 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants