|
| 1 | +.. _csharp-transactions: |
| 2 | + |
| 3 | +============ |
| 4 | +Transactions |
| 5 | +============ |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, multi-document |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 2 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use the {+driver-long+} to perform |
| 24 | +**transactions**. :manual:`Transactions </core/transactions/>` allow |
| 25 | +you to run a series of operations that do not change any data until the |
| 26 | +transaction is committed. If any operation in the transaction returns an |
| 27 | +error, the driver cancels the transaction and discards all data changes |
| 28 | +before they ever become visible. |
| 29 | + |
| 30 | +In MongoDB, transactions run within logical **sessions**. A |
| 31 | +:manual:`session </reference/server-sessions/>` is a grouping of related |
| 32 | +read or write operations that you intend to run sequentially. Sessions |
| 33 | +enable :manual:`causal consistency |
| 34 | +</core/read-isolation-consistency-recency/#causal-consistency>` for a |
| 35 | +group of operations or allow you to execute operations in an |
| 36 | +:website:`ACID transaction </basics/acid-transactions>`. MongoDB |
| 37 | +guarantees that the data involved in your transaction operations remains |
| 38 | +consistent, even if the operations encounter unexpected errors. |
| 39 | + |
| 40 | +When using the {+driver-short+}, you can create a new session from a |
| 41 | +``MongoClient`` instance as an ``IClientSession`` type. We recommend that you reuse |
| 42 | +your client for multiple sessions and transactions instead of |
| 43 | +instantiating a new client each time. |
| 44 | + |
| 45 | +.. warning:: |
| 46 | + |
| 47 | + Use an ``IClientSession`` only with the ``MongoClient`` (or associated |
| 48 | + ``MongoDatabase`` or ``MongoCollection``) that created it. Using an |
| 49 | + ``IClientSession`` with a different ``MongoClient`` results in operation |
| 50 | + errors. |
| 51 | + |
| 52 | +Methods |
| 53 | +------- |
| 54 | + |
| 55 | +Create an ``IClientSession`` by using either the synchronous ``StartSession()`` or |
| 56 | +the asynchronous ``StartSessionAsync()`` method on your ``MongoClient`` instance. |
| 57 | +You can then modify the session state by using the method set |
| 58 | +provided by the ``IClientSession`` interface. Select from the following |
| 59 | +:guilabel:`Synchronous Methods` and :guilabel:`Asynchronous Methods` |
| 60 | +tabs to learn about the methods to manage your transaction: |
| 61 | + |
| 62 | +.. tabs:: |
| 63 | + |
| 64 | + .. tab:: Synchronous Methods |
| 65 | + :tabid: synchronous-methods |
| 66 | + |
| 67 | + .. list-table:: |
| 68 | + :widths: 40 60 |
| 69 | + :header-rows: 1 |
| 70 | + |
| 71 | + * - Method |
| 72 | + - Description |
| 73 | + |
| 74 | + * - ``StartTransaction()`` |
| 75 | + - | Starts a new transaction, configured with the given options, on |
| 76 | + this session. Throws an exception if there is already |
| 77 | + a transaction in progress for the session. To learn more about |
| 78 | + this method, see the :manual:`startTransaction() page |
| 79 | + </reference/method/Session.startTransaction/>` in the Server manual. |
| 80 | + | |
| 81 | + | **Parameter**: ``TransactionOptions`` (optional) |
| 82 | + |
| 83 | + * - ``AbortTransaction()`` |
| 84 | + - | Ends the active transaction for this session. Throws an exception |
| 85 | + if there is no active transaction for the session or the |
| 86 | + transaction has been committed or ended. To learn more about |
| 87 | + this method, see the :manual:`abortTransaction() page |
| 88 | + </reference/method/Session.abortTransaction/>` in the Server manual. |
| 89 | + | |
| 90 | + | **Parameter**: ``CancellationToken`` |
| 91 | + |
| 92 | + * - ``CommitTransaction()`` |
| 93 | + - | Commits the active transaction for this session. Throws an exception |
| 94 | + if there is no active transaction for the session or if the |
| 95 | + transaction was ended. To learn more about |
| 96 | + this method, see the :manual:`commitTransaction() page |
| 97 | + </reference/method/Session.commitTransaction/>` in the Server manual. |
| 98 | + | |
| 99 | + | **Parameter**: ``CancellationToken`` |
| 100 | + |
| 101 | + * - ``WithTransaction()`` |
| 102 | + - | Starts a transaction on this session and runs the given callback. To |
| 103 | + learn more about this method, see the :manual:`withTransaction() page |
| 104 | + </reference/method/Session.withTransaction/>` in the Server manual. |
| 105 | + |
| 106 | + .. warning:: Handling Exceptions |
| 107 | + |
| 108 | + When catching exceptions within the callback function used by |
| 109 | + ``WithTransaction()``, you **must** rethrow the exception before |
| 110 | + exiting the try-catch block. Failing to do so can result in an |
| 111 | + infinite loop. For further details on how to handle exceptions in this |
| 112 | + case, see :manual:`Transactions </core/transactions/>` in the Server |
| 113 | + manual and select :guilabel:`C#` from the language dropdown to view |
| 114 | + the example. |
| 115 | + |
| 116 | + | |
| 117 | + | **Parameters**: ``Func <IClientSessionHandle, CancellationToken, Task<TResult>>``, ``TransactionOptions``, ``CancellationToken`` |
| 118 | + | **Return Type**: ``Task <TResult>`` |
| 119 | + |
| 120 | + .. tab:: Asynchronous Methods |
| 121 | + :tabid: asynchronous-methods |
| 122 | + |
| 123 | + .. list-table:: |
| 124 | + :widths: 40 60 |
| 125 | + :header-rows: 1 |
| 126 | + |
| 127 | + * - Method |
| 128 | + - Description |
| 129 | + |
| 130 | + * - ``StartTransaction()`` |
| 131 | + - | Starts a new transaction, configured with the given options, on |
| 132 | + this session. Throws an exception if there is already |
| 133 | + a transaction in progress for the session. To learn more about |
| 134 | + this method, see the :manual:`startTransaction() page |
| 135 | + </reference/method/Session.startTransaction/>` in the Server manual. |
| 136 | + | |
| 137 | + | **Parameter**: ``TransactionOptions`` (optional) |
| 138 | + |
| 139 | + * - ``AbortTransactionAsync()`` |
| 140 | + - | Ends the active transaction for this session. Throws an exception |
| 141 | + if there is no active transaction for the session or the |
| 142 | + transaction has been committed or ended. To learn more about |
| 143 | + this method, see the :manual:`abortTransaction() page |
| 144 | + </reference/method/Session.abortTransaction/>` in the Server manual. |
| 145 | + | |
| 146 | + | **Parameter**: ``CancellationToken`` |
| 147 | + | **Return Type**: ``Task`` |
| 148 | + |
| 149 | + |
| 150 | + * - ``CommitTransactionAsync()`` |
| 151 | + - | Commits the active transaction for this session. Throws an |
| 152 | + exception if there is no active transaction for the session or if the |
| 153 | + transaction was ended. To learn more about |
| 154 | + this method, see the :manual:`commitTransaction() page |
| 155 | + </reference/method/Session.commitTransaction/>` in the Server manual. |
| 156 | + | |
| 157 | + | **Parameter**: ``CancellationToken`` |
| 158 | + | **Return Type**: ``Task`` |
| 159 | + |
| 160 | + * - ``WithTransactionAsync()`` |
| 161 | + - | Starts a transaction on this session and runs the given callback. To |
| 162 | + learn more about this method, see the :manual:`withTransaction() page |
| 163 | + </reference/method/Session.withTransaction/>` in the Server manual. |
| 164 | + |
| 165 | + .. warning:: Handling Exceptions |
| 166 | + |
| 167 | + When catching exceptions within the callback function used by |
| 168 | + ``WithTransactionAsync()``, you **must** rethrow the exception |
| 169 | + before exiting the try-catch block. Failing to do so can result in an |
| 170 | + infinite loop. For further details on how to handle exceptions in this |
| 171 | + case, see :manual:`Transactions </core/transactions/>` in the Server |
| 172 | + manual and select :guilabel:`C#` from the language dropdown to view |
| 173 | + the example. |
| 174 | + |
| 175 | + | |
| 176 | + | **Parameters**: ``Func <IClientSessionHandle, CancellationToken, Task<TResult>>``, ``TransactionOptions``, ``CancellationToken`` |
| 177 | + | **Return Type**: ``Task <TResult>`` |
| 178 | + |
| 179 | +Example |
| 180 | +------- |
| 181 | + |
| 182 | +This example shows how you can create a session, create a |
| 183 | +transaction, and insert documents into multiple collections within the transaction |
| 184 | +through the following steps: |
| 185 | + |
| 186 | +1. Create a session from the client by using the ``StartSession()`` method. |
| 187 | +#. Use the ``StartTransaction()`` method to start a transaction. |
| 188 | +#. Insert documents into the ``books`` and ``films`` collections. |
| 189 | +#. Commit the transaction by using the ``CommitTransaction()`` method. |
| 190 | + |
| 191 | +.. io-code-block:: |
| 192 | + |
| 193 | + .. input:: /includes/fundamentals/code-examples/Transaction.cs |
| 194 | + :language: csharp |
| 195 | + :dedent: |
| 196 | + :start-after: begin-transaction |
| 197 | + :end-before: end-transaction |
| 198 | + |
| 199 | + .. output:: |
| 200 | + :language: console |
| 201 | + :visible: false |
| 202 | + |
| 203 | + Successfully committed transaction! |
| 204 | + |
| 205 | +Additional Information |
| 206 | +---------------------- |
| 207 | + |
| 208 | +To learn more about the concepts mentioned in this guide, see the |
| 209 | +following pages in the Server manual: |
| 210 | + |
| 211 | +- :manual:`Transactions </core/transactions/>` |
| 212 | +- :manual:`Server Sessions </reference/server-sessions/>` |
| 213 | +- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` |
| 214 | + |
| 215 | +API Documentation |
| 216 | +~~~~~~~~~~~~~~~~~ |
| 217 | + |
| 218 | +To learn more about any of the types or methods discussed in this |
| 219 | +guide, see the following API Documentation: |
| 220 | + |
| 221 | +- `IClientSession <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.html>`__ |
| 222 | +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ |
| 223 | +- `StartTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.StartTransaction.html>`__ |
| 224 | +- `AbortTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransaction.html>`__ / `AbortTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransactionAsync.html>`__ |
| 225 | +- `CommitTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransaction.html>`__ / `CommitTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransactionAsync.html>`__ |
| 226 | +- `WithTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransaction.html>`__ / `WithTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransactionAsync.html>`__ |
| 227 | +- `TransactionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.TransactionOptions.html>`__ |
0 commit comments