Harry
Harry

Reputation: 4946

EF Core transactions - am I doing it right?

What I know is EF creates transaction for DbContext.SaveChanges. But I need a block of operations including inserts and I need identity results from them to complete my sequence. So what I do looks like this:

using var dbTransaction = context.DataBase.BeginTransaction();
try {
    context.Add(myNewEntity);
    context.SaveChanges();
    otherEntity.RefId = myNewEntity.Id;
    context.Update(otherEntity);
    // some other inserts and updates
    context.SaveChanges();
    dbTransaction.Commit();
}
catch {
    dbTransaction.Rollback();
    throw;
}

So I call SaveChanges on inserts to get identities and not to break relations. It looks like transactions in transactions. Is it correct? Is it how it should be done? I mean - Commit doesn't require SaveChanges? I assume it just saves the changes, but I want to be sure.

Upvotes: 1

Views: 2729

Answers (1)

Serge
Serge

Reputation: 43860

Your code will be working properly, but I prefer to do it this way:

try {
    context.Add(myNewEntity);
   var result= context.SaveChanges();
    if(result==0){
       dbTransaction.Rollback();
        ... return  error
     }
    otherEntity.RefId = myNewEntity.Id;
    context.Update(otherEntity);
    // some other inserts and updates
    result=context.SaveChanges();
if(result==0){
       dbTransaction.Rollback();
        ... return  error
     }
    dbTransaction.Commit();
}
catch {
    dbTransaction.Rollback();
    throw;
}

It is very usefull if for example you update or add or delete several records. In this case the result will return the number of effected records and instead of result==0 I usually use if result < ...effected records I expect.

Upvotes: 1

Related Questions