How to work with transactions that rely on reading?

Hello. How to work with transactions that rely on reading? It turns out that the read operations are not blocking.

Example I should commit Transaction if ‘A’ = 50 but ‘A’ can change from other outside system\thread.

 var A = a.Find(session, f => f.UserId == 1).FirstOrDefault();

 var C = c.Update(session, f => f.x == 1, {x: 111});
    // <<<<----- For example , here another system has already replaced 50 by 100 , and we still have 50 and the conditions are met , although it is no longer correct --- >>>
    if (A.Plamp == 50)
    {
        session.commitTransaction();
    }

How to write such a transaction correctly?

up
I read your blog article about transactions , but I didn 't find a solution for my situation

Hi @alexov_inbox,

As you have discovered in the case above, read operation does not lock a document from being modified. Worth mentioning that in the code snippet above the condition check for A.Plamp is performed on the client side and not on the database server side.

In the above example, one way to invalidate the update operation on C is to insert Plamp into C. For example:

var C = c.Update(session, f => f.x == 1, {x: 111, Plamp: 50});

If the value of Plamp has been updated to 100, the transaction will throw a WriteConflict. The client application would have to handle this error and apply a retry logic appropriately. See also Drivers API: Transactions for more information.

Regards,
Wan.

2 Likes

Thx for answer.

You say about throw “abort transaction” by hand on client side check after update(and update change to findAndUpdate)?

Do I understand correctly that you are talking about this option?

 var A = a.Find(session, f => f.UserId == 1).FirstOrDefault();

 var C = c.FindAndUpdate(session, f => f.x == 1, {x: 111, Plamp: A.Plamp});

    if (C.Plamp != 50)
    {
        session.AbortTransaction();
    }

Hi @alexov_inbox,

Not quite. By including A.Plamp value in collection C, the application then needs to handle WriteConflict error that would be thrown by the server. The application should not need to perform a client-side conditional check anymore i.e. the if (C.Plamp != 50)

here another system has already replaced 50 by 100 , and we still have 50 and the conditions are met

Do the other system will also update the value of Plamp in collection C ? This is the significant part to create the conflict.

Regards,
Wan.