【发布时间】:2021-03-27 19:17:12
【问题描述】:
我在 .net core 3.1.in 上进行了项目,其中我使用了 mongodb 作为数据库(mongo c# 驱动程序)。
在这里,我在模型上有字段字典
MongoDB.Driver.MongoWriteException:写入操作导致错误。 不能使用非数字参数递增:{monthlyBalance.12: "3500"} ---> MongoDB.Driver.MongoBulkWriteException`1[FinanceAPI.Models.CompanyLedger]:批量写入操作导致一个或多个错误。 不能使用非数字参数递增:{monthlyBalance.12: "3500"}
这是我的代码和模型。我怎样才能解决这个问题 ? 我究竟做错了什么? 谢谢 !! CompanyLedger.cs
public class CompanyLedger : DefaultProperties
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string _id { get; set; }
public string ledgerTemplateId { get; set; }
public string companyId { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int periodId { get; set; }
public List<CategoryItem> categories { get; set; }
[BsonRepresentation(BsonType.Decimal128)]
public decimal openingBalance { get; set; }
[BsonRepresentation(BsonType.Decimal128)]
public decimal currentBalance { get; set; }
[BsonRepresentation(BsonType.Decimal128)]
public decimal closingBalance { get; set; }
public Dictionary<string, decimal> monthlyBalance { get; set; } = new Dictionary<string, decimal>();
public Dictionary<string, decimal> dayBalance { get; set; } = new Dictionary<string, decimal>();
}
$inc 运算符使用
public virtual long CreditMonthlyBalanceOfLedger(string id, decimal amount, DateTime date, string userID)
{
var ledgerTask = Get(id: id);
var month = date.Month.ToString();
var ledger = ledgerTask.Result;
// if month name contain in dictionary
if (ledger.monthlyBalance.ContainsKey(month))
{
var update = Builders<CompanyLedger>.Update.Inc(x => x.monthlyBalance[month], amount).Set(x => x.modifiedById, userID).Set(x => x.modifiedOn, DateTime.Now);
return db.CompanyLedger.UpdateOne(x => x._id == id, update).ModifiedCount;
}
else
{
var update = Builders<CompanyLedger>.Update.Set(x => x.monthlyBalance[month], amount).Set(x => x.modifiedById, userID).Set(x => x.modifiedOn, DateTime.Now);
return db.CompanyLedger.UpdateOne(x => x._id == id, update, new UpdateOptions() { IsUpsert = true }).ModifiedCount;
}
}
【问题讨论】:
标签: mongodb dictionary asp.net-core mongodb-query