我正在使用官方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)
答案 0 :(得分:2)
我要做的是在单个事务中创建多个索引
多文档事务中不允许影响数据库目录的操作,例如创建或删除集合或索引。
有关详细信息,另请参阅MongoDB Transactions and CRUD Operations。
交易中支持的