-
Notifications
You must be signed in to change notification settings - Fork 2
1 Mapping classes to the database
As you saw in the examples, there are no annotations on the classes that you want to persist in the database. All the mappings are done in separate components, in order to not pollute objects with database concerns. The MongoBasic philosophy states that you will need one mapping per class. So, for each class that you want to persist in the database, you will need a class map. This is similar to other popular ORM frameworks.
In order to create a mapping, you simply create a new class that derives from the MongoClassMap abstract class. Then provide an implementation for the MapEntity method. Inside this method, you can use all the options of the official mongo c# driver. For more information on mapping, you can check out their site: https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/tutorial/serialize-documents-with-the-csharp-driver.html
public class PersonMap: MongoClassMap<Person>
{
protected override void MapEntity(BsonClassMap<Person> cm)
{
//when note auto mapping, specify id generator for id property
cm.MapIdField(x => x.Id).SetIdGenerator(new ObjectIdGenerator());
cm.MapProperty(x => x.Name);
cm.MapProperty(x => x.Age);
}
}
NOTE
Each class that you want to map, needs to have an 'Id' property. Depending on the Id generation method that you will use, this property can be of type 'string', 'ObjectId', 'int' or 'long';