Home > Enterprise >  Mongo DB in c#: Transaction not working - what I'm doing wrong?
Mongo DB in c#: Transaction not working - what I'm doing wrong?

Time:06-29

I have a situation like this:

var mongoClient = new MongoClient("connection-bla-bla");
var mongoDB = mongoClient.GetDatabase("db-name");
using (var session = mongoDB.Client.StartSession())
{
    session.StartTransaction();
    var collection = mongoDB.GetCollection<Rec>("collectionName");
    collection.InsertOne(new Rec() { Name = "Record1" });
    collection.InsertOne(new Rec() { Name = "Record2" });
    session.CommitTransaction();
}

This code works quite fine, Record1 and Record2 are written.

However, when i try this ...

var mongoClient = new MongoClient("connection-bla-bla");
var mongoDB = mongoClient.GetDatabase("db-name");
using (var session = mongoDB.Client.StartSession())
{
    session.StartTransaction();
    var collection = mongoDB.GetCollection<Rec>("collectionName");
    collection.InsertOne(new Rec() { Name = "Record1" });
    if (DateTime.UtcNow > DateTime.MinValue) throw new Exception("Bad things happens");
    collection.InsertOne(new Rec() { Name = "Record2" });
    session.CommitTransaction();
}

... Record1 is written, even the transaction is not comitted. I guess I miss here something, but have no clue what. Thanks for code correction.

CodePudding user response:

In order to use the transaction, you need to specify the session when calling the insert commands:

var mongoClient = new MongoClient("connection-bla-bla");
var mongoDB = mongoClient.GetDatabase("db-name");
using (var session = mongoDB.Client.StartSession())
{
    session.StartTransaction();
    var collection = mongoDB.GetCollection<Rec>("collectionName");
    collection.InsertOne(session, new Rec() { Name = "Record1" });
    if (DateTime.UtcNow > DateTime.MinValue) throw new Exception("Bad things happens");
    collection.InsertOne(session, new Rec() { Name = "Record2" });
    session.CommitTransaction();
}

There are overloads for various write commands that accept the session. See this link for details.

  • Related