Mongodb $inc operator in dictionary in .Net core

Viewed 273

I've project on .net core 3.1.in which i've used mongodb for database(mongo c# driver). here i've field dictionary<string,decimal> on model. i'm using $inc operator for increment decimal value of dictionary in database.the value of dictionary is in decimal so it will take as in string. the error something like that

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"}

here is my code and model. how can i fix this ? what am i doing wrong? Thank you !! 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 operator use

 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;
        }
    }
1 Answers

solution is you need to register serializer. once i registered decimal serializer in startup.cs it works. BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));

Related