Reputation: 2172
I am using the official C# MongoDb strongly typed driver version 2.7.0-beta0001 to interact with MongoDB.
What I am trying to do is to create multiple indexes in a single transaction but I always get "Message "Object reference not set to an instance of an object".
Even if I didn't use the transactions by removing the session variable, I also get the same exception.
Here is my code:
var client = new MongoClient(ConnectionString);
var database = client.GetDatabase(DatabaseName);
var Coupons = database.GetCollection<Coupon>("Coupons");
var Books = database.GetCollection<Book>("Books");
var session = await database.Client.StartSessionAsync();
session.StartTransaction();
try {
var options = new CreateIndexOptions() { Unique = true };
var couponIndex = new IndexKeysDefinitionBuilder<Coupon>().Ascending(c => c.CouponNumber);
var couponIndexModel = new CreateIndexModel<Coupon>(couponIndex, options);
await Coupons.Indexes.CreateOneAsync(session, couponIndexModel);//Exception happens at this line
var bookIndex = new IndexKeysDefinitionBuilder<Book>().Ascending(c => c.BookNumber);
var bookIndexModel = new CreateIndexModel<Book>(bookIndex, options);
await Books.Indexes.CreateOneAsync(session, bookIndexModel);
await session.CommitTransactionAsync();
} catch (Exception ex) {
await session.AbortTransactionAsync();
Console.WriteLine(ex.StackTrace);
}
Here are the exception details:-
Message "Object reference not set to an instance of an object."
Source "MongoDB.Driver"
StackTrace "at MongoDB.Driver.MongoIndexManagerBase`1.ToCreateManyIndexesOptions(CreateOneIndexOptions options)
at MongoDB.Driver.MongoIndexManagerBase`1.CreateOneAsync(IClientSessionHandle session, CreateIndexModel`1 model, CreateOneIndexOptions options, CancellationToken cancellationToken)
TargetSite {MongoDB.Driver.CreateManyIndexesOptions ToCreateManyIndexesOptions(MongoDB.Driver.CreateOneIndexOptions)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
{System.NullReferenceException: Object reference not set to an instance of an object.
at MongoDB.Driver.MongoIndexManagerBase`1.ToCreateManyIndexesOptions(CreateOneIndexOptions options)
at MongoDB.Driver.MongoIndexManagerBase`1.CreateOneAsync(IClientSessionHandle session, CreateIndexModel`1 model, CreateOneIndexOptions options, CancellationToken cancellationToken)
Upvotes: 0
Views: 1801
Reputation: 18835
What I am trying to do is to create multiple indexes in a single transaction
Operations that affect the database catalog, such as creating or dropping a collection or an index, are not allowed in multi-document transactions.
See also MongoDB Transactions and CRUD Operations for more information.
MongoDB commands supported in transactions are:
Upvotes: 2