Hi @ZargorNET, and welcome to the forum
You can utilise SetDefaultValue()
to assign a value to a field if the document does not have a value for the field (null is a value) during deserialisation.
For example if you have the following document stored in the database :
{
"_id": ObjectId("5f583cc562d0ce4a58c7da08"),
"Name": "X"
}
With class mapping example as below:
public class MyClass
{
[BsonId]
private ObjectId Id {get; set;}
public string Name {get; set;}
public List<string> MyList {get; set;}
}
You can register and set a default value for deserialisation as below:
BsonClassMap.RegisterClassMap<MyClass>(cm =>
{
cm.AutoMap();
cm.GetMemberMap(x => x.MyList).SetDefaultValue(new List<string>());
});
This should deserialise MyList
value into []
. For more information see also MongoDB .NET/C# Mapping Classes
Without knowing more of the context, you could also declare a constructor the class. This should help defined a default value before inserting to the database. For example:
public class MyClass
{
[BsonId]
private ObjectId Id {get; set;}
public string Name {get; set;}
public List<string> MyList {get; set;}
public MyClass ()
{
Name = "";
MyList = new List<string>();
}
}
Regards,
Wan.