dotnet / dotnet/efcore

SQL Server: Support INSTEAD OF INSERT triggers

Open
#35,535 4 comments 6 reactions 0 assignees View on GitHub
area-save-changes area-sqlserver customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### 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](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/breaking-changes?tabs=v7#sql-server-tables-with-triggers-or-certain-computed-columns-now-require-special-ef-core-configuration).
The table is defined with `.HasTrigger(...)`, which appears to have no effect. Using `UseSqlOutputClause(false)` also has no effect.
Have seen [this issue](https://learn.microsoft.com/en-us/answers/questions/2112283/how-to-resolve-efcore-8-saving-to-table-with-trigg) 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](https://stackoverflow.com/questions/908257/instead-of-trigger-in-sql-server-loses-scope-identity).

.net 9
EF version 9.0.1

### Your code

```csharp

```

### Stack traces

```text

```

### Verbose output

```text

```

### EF Core version

9.0.1

### Database provider

_No response_

### Target framework

_No response_

### Operating system

_No response_

### IDE

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.