Search code examples
c#nhibernatenhibernate-mappingnhibernate-mapping-by-code

Generate sequential Id for primary key column in NHibernate


How can I generate a Sequential guid for a primary key column in NHibernate. I know how to do that auto increment stuff. But I don't know how to create a sequential Guid for primary key.

In the database, data type of Id column is uniqueidentifier. I've checked the official docs and some other web search results. But I'm not able to find any solution. Here is what I have now:

public UserMap()
{
    Table("Users");
    Id(x => x.Id);
    Property(x => x.Username, x => x.NotNullable(true));
    Property(x => x.Email, x => x.NotNullable(true));
    Property(x => x.PasswordHash, x =>
    {
        x.NotNullable(true);
        x.Column("password_hash");
    });
}

Solution

  • I do that like so:

    In my business entity classes

    public abstract class EntityBase : IEntity
    {
        public virtual Guid Id { get; protected set; }
        ...
    }
    

    The fluent mapping:

    Id(x => x.Id).GeneratedBy.GuidComb();
    

    Read this about Guid.comb