MongoDB .NET - Binding data to model classes but unable to read Integer value

45 views Asked by At

I have a collection called "transaction" like this

{
    "approverSpv": {
        "id": 176,
        "isApproved": true
    },
    "approverManager": {
        "id": 176,
        "isApproved": true
    }
}

And I want to read those Approver's id. Here are my classes:

public class ApproverManager
{
    public int id { get; set; }

    public bool isApproved { get; set; }
}


public class ApproverSpv
{
    public int id { get; set; }

    public bool isApproved { get; set; }
}

public class Transaction() 
{
     public ApproverSpv approverSpv { get; set; }
    
     public ApproverManager approverManager { get; set; }
}

And then I tried this code from C#:

var transactionParts = database.GetCollection<Transaction>("transaction").AsQueryable<Transaction>().ToList();

The code returned always shows 0 to every id inside ApproverSpv and ApproverManager but successfully gets the actual value of isApproved: true or false.

May I know, what did I miss here? How to get the actual value of each id inside the Approver?

1

There are 1 answers

0
Yong Shun On BEST ANSWER

By default, the property name: Id is treated and mapped to _id in MongoDB .NET. To prevent the default deserialization, you should apply the BsonNoId attribute to your classes.

using MongoDB.Bson.Serialization.Attributes;

[BsonNoId]
public class ApproverManager
{
    public int id { get; set; }

    public bool isApproved { get; set; }

}

[BsonNoId]
public class ApproverSpv
{
    public int id { get; set; }

    public bool isApproved { get; set; }
}