Search code examples
c#nhibernatepostgresqlfluent-nhibernate

Auto Increment in FLuent Nhibernate and PostgreSQL


I`m a newbie in Fluent Nhibernate.

I have a PostgreSQL database and what I want is a generated id with auto increment. I have not seen feature auto increment in PostgreSQL and I understand that to use auto increment in PostgreSQL I have to create a sequence.

Is there another way besides sequences?

If create sequence is the only way, can you tell me how I should mapping it? I tried to use this and had no success:

mapping.Id(x => x.Id, "id").GeneratedBy.Sequence("hibernate-sequence");

I have created hibernate-sequence before using it.

Regards


Solution

  • Strange, but with your code an insertion works fine, if you call Save(Object) instead of SaveOrUpdate(Object)

    Edit #1

    That's what worked for me.

    Entity:

    public class Human
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
    }
    
    public class HumanMap : ClassMap<Human>
    {
        public HumanMap()
        {
            this.Id(x => x.ID).CustomSqlType("Serial").GeneratedBy.Native();
            this.Map(x => x.Name);
        }
    }
    

    And configuration with schema export:

    static ISessionFactory CreateSF()
    {
        return Fluently
        .Configure()
        .Database(PostgreSQLConfiguration.Standard.ConnectionString("Server=127.0.0.1;Port=5432;Database=fnhtest;User=postgres;Password=password"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
        .ExposeConfiguration(cfg => { new SchemaExport(cfg).Create(false, true); })
        .BuildSessionFactory(); 
    }