使用 C# Mongodb 强类型驱动程序在事务中创建多个索引

Create multiple indexes in a transaction using C# Mongodb strongly typed driver

我正在使用官方 C# MongoDb 强类型驱动程序版本 2.7.0-beta0001 与 MongoDB 交互。

我想做的是在单个事务中创建多个索引,但我总是得到 "Message "未设置对象实例的对象引用。

即使我没有通过删除会话变量来使用事务,我也会得到同样的异常。

这是我的代码:

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);
}

以下是异常详情:-

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)

What I am trying to do is to create multiple indexes in a single transaction

多文档事务中不允许执行影响数据库目录的操作,例如创建或删除集合或索引。

另请参阅 MongoDB Transactions and CRUD Operations 了解更多信息。

MongoDB commands 交易中支持的是: