I have a simple situation where I’m using EF Core and TransactionScope
(I cannot use, so don’t recommend it, context.Database.UseTransaction
or anything else from the DbContext, the first actions the transaction maintains aren’t related to a DB so there is no DbContext) from System.Transactions
, however (as we know) EF doesn’t maintain any concept of order for inserts, so if you have
var a = new o1 { Id = "Id1" }
ctx.AddAsync(a);
// some other code
var b = new o2 { Id = "Id2", aId = a.Id }
ctx.AddAsync(b);
await ctx.SaveChangesAsync()
There’s a good chance you get a foreign key error as there’s no guarantee a
will save before b
, so we’re supposed to add await ctx.SaveChangesAsync()
after calling ctx.AddAsync(a);
like this.
var a = new o1 { Id = "Id1" }
ctx.AddAsync(a);
await ctx.SaveChangesAsync()
// some other code
var b = new o2 { Id = "Id2", aId = a.Id }
ctx.AddAsync(b);
await ctx.SaveChangesAsync()
Here we have a problem though.
That works all well and fine when you don’t have a TransactionScope
. Once you wrap the above in a TransactionScope
you end up with a Timeout
being generated on the second call to await ctx.SaveChangesAsync()
using (var tx = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled))
{
var a = new o1 { Id = "Id1" }
ctx.AddAsync(a);
await ctx.SaveChangesAsync()
// some other code
var b = new o2 { Id = "Id2", aId = a.Id }
ctx.AddAsync(b);
await ctx.SaveChangesAsync()
// Never reaches here because the above line times out
tx.Commit();
}
I’ve not found a solution to this. Has anyone else?