[英]Create multiple indexes in a transaction using C# Mongodb strongly typed driver
我正在使用官方的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.