//准备转账
        private TransactionDocument PrepareTransfer(double amt, string source, string destination)
        {
            string strGUID = System.Guid.NewGuid().ToString("N"); //类似e0a953c3ee6040eaa9fae2b667060e09
            //创建事务文档
            TransactionDocument tDoc = new TransactionDocument
            {
                _id   = strGUID, //这个应该是随机生成的一个串
                State = "new",
                Ts    = DateTime.Now,
                Amt   = amt,
                Src   = source,
                Dst   = destination
            };
            //将事务文档插入事务集合
            bool isSu = mongoDBService.Insert(TransactionCollectionName, tDoc);

            if (!isSu)
            {
                throw new Exception("构建事务文档失败!");
            }

            FilterDefinitionBuilder <Account> filterBuilder = Builders <Account> .Filter;
            //更新source账户
            FilterDefinition <Account> filterS = filterBuilder.Eq(m => m._id, source) & filterBuilder.Gte(m => m.Balance, amt);
            UpdateDefinition <Account> updateS = Builders <Account> .Update.Push(m => m.Txns, tDoc._id).Inc(m => m.Balance, -amt);

            UpdateResult updateResult = mongoDBService.DocumentUpdate(AccountsCollectionName, filterS, updateS);

            //检测更新是否成功
            bool isSuccess = updateResult.ModifiedCount > 0 && updateResult.ModifiedCount == updateResult.MatchedCount?
                             true:false;

            if (!isSuccess)
            {
                mongoDBService.Delete <TransactionDocument>(TransactionCollectionName, m => m._id == tDoc._id);
                throw new Exception("更新source账户失败");
            }

            //更新destination账户
            FilterDefinition <Account> filterD = filterBuilder.Eq(m => m._id, destination);
            var updateD = Builders <Account> .Update.Push(m => m.Txns, tDoc._id).Inc(m => m.Balance, amt);

            UpdateResult updateResultD = mongoDBService.DocumentUpdate(AccountsCollectionName, filterD, updateD);
            bool         isSuccessD    = updateResultD.ModifiedCount > 0 && updateResultD.ModifiedCount == updateResultD.MatchedCount ?
                                         true : false;

            if (!isSuccessD)
            {
                throw new Exception("更新destination账户失败");
            }
            return(tDoc);
        }
Beispiel #2
0
 /// <summary>
 /// 删除文档
 /// </summary>
 public void Delete()
 {
     mongoDBService.Delete <Model2>(collectionName, m => m.Field2A.Equals(DateTime.Parse("2016-09-08")));
 }