I am looking into building an interceptor for my application. One of the interceptors I need is for when I use transactions. While playing around with one, I noticed that it is always triggered - even when I have not started a transaction. Is this expected behaviour?
The following code gives me this output:
transaction triggered
transaction triggered
using System;
using System.Data.Common;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
var context = new TestContext();
context.Database.EnsureDeleted();
// this triggers the transaction interceptor. I assume a transaction is started when creating a db.
context.Database.EnsureCreated();
var test = new TestClass()
{
Name = "Morten",
};
context.TestClasses.Add(test);
context.SaveChanges(); // this triggers the transaction interceptor - which I didn't expect
class TestContext : DbContext
{
public DbSet<TestClass> TestClasses { get; private set; } = null!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.AddInterceptors(new TestTransactionInterceptor());
optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=Test;User ID=myuser;Password=mypassword;Multiple Active Result Sets=True");
}
}
class TestTransactionInterceptor : DbTransactionInterceptor
{
public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData)
{
Console.WriteLine("transaction triggered");
return;
}
}
class TestClass
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
The cause is an implicit transaction.
By default, if the database provider supports transactions, all changes in a single call to SaveChanges are applied in a transaction.
So this means that despite no explicit transaction being created, ef core will do it implicitly - which is what causes the interceptor to be triggered.
https://learn.microsoft.com/en-us/ef/core/saving/transactions#default-transaction-behavior
Thanks to: https://twitter.com/josvandertil/status/1534871408517558274?t=Dl4YZKsTFbWBwgCsttaVlg&s=19
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With