Fork me on GitHub

Sequential Identifiers with Hilo Edit on GitHub


The Hilo sequence generation can be customized with either global defaults or document type specific overrides. By default, the Hilo sequence generation in Marten increments by 1 and uses a "maximum lo" number of 1000.

To set different global defaults, use the StoreOptions.HiloSequenceDefaults property like this sample:


var store = DocumentStore.For(_ =>
{
    _.HiloSequenceDefaults.MaxLo = 55;
    _.Connection(ConnectionSource.ConnectionString);
    _.DatabaseSchemaName = "sequences";
});

It's also possible to use one sequence with multiple document types by specifying the same "sequence name".


var store = DocumentStore.For(_ =>
{
    _.HiloSequenceDefaults.SequenceName = "Entity";
    _.Connection(ConnectionSource.ConnectionString);

    _.DatabaseSchemaName = "sequences";
});

To override the Hilo configuration for a specific document type, you can decorate the document type with the [HiloSequence] attribute as in this example:


[HiloSequence(MaxLo = 66, SequenceName = "Entity")]
public class OverriddenHiloDoc
{
    public int Id { get; set; }
}

You can also use the MartenRegistry fluent interface to override the Hilo configuration for a document type as in this example:


var store = DocumentStore.For(_ =>
{
    // Overriding the Hilo settings for the document type "IntDoc"
    _.Schema.For<IntDoc>()
        .HiloSettings(new HiloSettings {MaxLo = 66});

    _.Connection(ConnectionSource.ConnectionString);

    _.DatabaseSchemaName = "sequences";
});

Set the Identifier Floor

Marten 1.2 adds a convenience method to reset the "floor" of the Hilo sequence for a single document type:


var store = DocumentStore.For(opts =>
{
    opts.Connection(ConnectionSource.ConnectionString);
    opts.DatabaseSchemaName = "sequences";
});

// Resets the minimum Id number for the IntDoc document
// type to 2500
store.Tenancy.Default.ResetHiloSequenceFloor<IntDoc>(2500);

This functionality was added specifically to aid in importing data from an existing data source. Do note that this functionality simply guarantees that all new id's assigned for the document type will be higher than the new floor. It is perfectly possible and even likely that there will be some gaps in the id sequence.