Fork me on GitHub

Document Identity Edit on GitHub


Besides being serializable, Marten's only other requirement for a .Net type to be a document is the existence of an identifier field or property that Marten can use as the primary key for the document type. The Id can be either a public field or property, and the name must be either id or Id or ID. As of this time, Marten supports these Id types:

  1. String. It might be valuable to use a natural key as the identifier, especially if it is valuable within the Identity Map feature of Marten Db. In this case, the user will be responsible for supplying the identifier.
  2. Guid. If the id is a Guid, Marten will assign a new value for you when you persist the document for the first time if the id is empty. And for the record, it's pronounced "gwid".
  3. CombGuid is a sequential Guid algorithm. It can improve performance over the default Guid as it reduces fragmentation of the PK index. (More info soon)
  4. Int or Long. As of right now, Marten uses a HiLo generator approach to assigning numeric identifiers by document type. Marten may support Postgresql sequences or star-based algorithms as later alternatives.
  5. When the ID member of a document is not settable or not-public a NoOpIdGeneration strategy is used. This ensures that Marten does not set the ID itself, so the ID should be generated manually.
  6. A Custom ID generator strategy is used to implement the ID generation strategy yourself.
When using a `Guid`/`CombGuid`, `Int`, or `Long` identifier, Marten will ensure the identity is set immediately after calling `IDocumentSession.Store` on the entity.

See these topics for more information about specific Id types:

You can see some example id usages below:


public class Division
{
    // String property as Id
    public string Id { get; set; }
}

public class Category
{
    // Guid's work, fields too
    public Guid Id;
}

public class Invoide
{
    // int's and long's can be the Id
    // "id" is accepted
    public int id { get; set; }
}

Overriding the Choice of Id Property/Field

If you really want to -- or you're migrating existing document types from another document database -- Marten provides the [Identity] attribute to force Marten to use a property or field as the identifier that doesn't match the "id" or "Id" or "ID" convention:


public class NonStandardDoc
{
    [Identity]
    public string Name;
}