Search code examples
c#.netmongodbasp.net-coreinsert

Insert a document to a MongoDB


I am trying to build a simple API connected to a MongoDB. I have customers and I want to add those to the DB

This is my customer class:

public class Customer : BaseCustomer
{
    public Customer(string name, string surname, string address) : base(name, surname, address)
    {
    }
}

It inherits from BaseCustomer:

public class BaseCustomer
{
    public string Key { get; }
    public string Name { get;  }
    public string Surname { get; }
    public string Address { get; }

    protected BaseCustomer(string name, string surname, string address)
    {
        Name = name;
        Surname = surname;
        Address = address;
        Key = "test";
    }
}

I just simply insert it like this:

public void CreateEntry(TObject o)
{
    _mongoCollection.InsertOne(o);
}

Why is everything displayed except the key? (Img1)

If I change the Key property in BaseCustomer to public string Key { get; set; } only the key appears (Img2) Why???

I just simply want all properties appearing in the DB entry

Thanks in advance


Solution

  • You should let the MongoDB knows about it. Serializers in MongoDB ignore properties with private setters by default, assuming they cannot be directly set (for instance, during deserialization). It is possible to set the value of the Key property in BaseCustomer during deserialization when the Key property is changed to have a public setter.

    The [BsonElement] attribute can be used to specify the name of the Key property in the database entry without having a public setter.

    something like would help:

    using MongoDB.Bson.Serialization.Attributes;
    
    public class BaseCustomer
    {
      [BsonElement("Key")]
      public string Key { get;  }
      public string Name { get;  }
      public string Surname { get; }
      public string Address { get; }
    
    protected BaseCustomer(string name, string surname, string address)
    {
        Name = name;
        Surname = surname;
        Address = address;
        Key = "test";
    }
    

    }