我在 .net core 3.1 上进行了项目,其中我使用 mongodb 作为数据库(mongo c# 驱动程序)。
这里我在模型上有字段字典
MongoDB.Driver.MongoWriteException: A write operation resulted in an error. Cannot increment with non-numeric argument: {monthlyBalance.12: "3500"} ---> MongoDB.Driver.MongoBulkWriteException`1[FinanceAPI.Models.CompanyLedger]: A bulk write operation resulted in one or more errors. Cannot increment with non-numeric argument: {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;
}
}
最佳答案
解决方案是您需要注册序列化器。
一旦我在 startup.cs
中注册了十进制序列化器,它就可以工作了。
BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));
关于.Net core字典中的Mongodb $inc运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65334946/