Fix database trigger issue in .NET 7, Entity Framework

Fix database trigger issue in .NET 7, Entity Framework

Original YouTube Logo

Article have related YouTube video

So when i tried out Entity Framework in .NET 7 i stumbled upon this annoying error that tells me that the database has triggers so it throws an exception. In this case a DbUpdateException.

28-02-2023 |

Entity Framework
.NET
Errors

This is the exception i get:

Microsoft.EntityFrameworkCore.DbUpdateException: Could not save changes because the target table has database triggers. Please configure your entity type accordingly, see https://aka.ms/efcore-docs-sqlserver-save-changes-and-triggers for more information.
SqlException: The target table 'dbo.Employee' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.

In a prettier format:

In Microsoft's EF documentation they point out that in the new version 7 of EF Core, they use a better technique to make EF perform much better.

However this doesnt come without the issue of that we need to tell EF Core 7 if there is any tables in your database that uses triggers or have unsupported computed columns.

In my case i don't believe that i actually have any of these, however i get the error anyway. But the fix help me even though I should not be affected of the issue.

Fixing the SqlException

So to fix it we need to tell EF Core 7 that it should use the old technique and eventually not using the new improved technique to get data from the database, which is sad, however in Microsoft's own documentation it sounds like that this is the only way to solve it.

Inside your context file you want to tell Entity Framework which tables that have triggers (Even though you don't believe to have any). So inside your OnModelCreating but the following code:

The whole line makes sense, except what the value inside the HasTrigger() should be. Regarding to the documentation it really doesnt matter what you specify, just call it something, and then it will roll the EF back to use the older technique of manipulating the data from the database.

Also remember to use your own model. In my case it was Employee, you might have another model for your table.


Like what you see?


New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.

ZetBit

Subscribe to ZetBits Newsletter