【问题标题】:Create multiple indexes in a transaction using C# Mongodb strongly typed driver使用 C# Mongodb 强类型驱动程序在事务中创建多个索引
【发布时间】:2018-05-20 12:14:33
【问题描述】:

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

我想做的是在单个事务中创建多个索引,但我总是收到“消息“对象引用未设置为对象的实例”。

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

这是我的代码:

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)

【问题讨论】:

    标签: c# .net mongodb mongodb-query mongodb-.net-driver


    【解决方案1】:

    我要做的是在单个事务中创建多个索引

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

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

    事务中支持的MongoDB commands有:

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多