【问题标题】:Mongodb $inc operator in dictionary in .Net core.Net核心字典中的Mongodb $inc运算符
【发布时间】:2021-03-27 19:17:12
【问题描述】:

我在 .net core 3.1.in 上进行了项目,其中我使用了 mongodb 作为数据库(mongo c# 驱动程序)。 在这里,我在模型上有字段字典。我正在使用 $inc 运算符来增加数据库中字典的十进制值。字典的值是十进制的,所以它会像字符串一样。类似的错误

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


    【解决方案1】:

    解决方案是您需要注册序列化程序。 一旦我在startup.cs 中注册了十进制序列化程序,它就可以工作了。 BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 2022-12-12
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多