-
Notifications
You must be signed in to change notification settings - Fork 2
5 Auto Increment Id Generator
Dan Geabunea edited this page Jul 22, 2015
·
1 revision
The MongoBasic library allows you to use auto-incremented id generation, if you want. The id generation strategy can be specified per class mapping. Here is an example:
public class Vehicle
{
//we need to have an Id property of type int or long
public long Id { get; set; }
public string Model { get; set; }
public string Make { get; set; }
}
```
```c#
public class VehicleMap:MongoClassMap<Vehicle>
{
//add constructor with id generator parameter
public VehicleMap(IIdGenerator idGenerator):base(idGenerator)
{
//leave constructor body empty, just pass the idGenerator to the
//base class constructor
}
protected override void MapEntity(BsonClassMap<Vehicle> cm)
{
//set idGenerator to the one we passed in the constructor
cm.MapIdField(x => x.Id).SetIdGenerator(this.IdGenerator);
cm.AutoMap();
}
}
public class MySessionMongoFactory : AbstractMongoSessionFactory
{
public MySessionMongoFactory(MongoSessionFactoryConfig mongoSettings) : base(mongoSettings)
{
}
protected override void AfterSessionFactoryInitialized(MongoDatabase mongoDatabase)
{
//instantiate VehicleMap class with correct constructor
//the AutoIncrementIdGenerator will use long type for id fields, for the 'Vehicles' collection
RegisterClassMap(new VehicleMap(new AutoIncrementIdGenerator<long>(mongoDatabase, "Vehicles")));
}
}