Postgresql Identity Column

32 views
Skip to first unread message

Prakash Bhatta

unread,
Apr 6, 2023, 3:17:53 PM4/6/23
to nhusers
Hi, I am using Postgresql and Nhibernate and in my table I have Identity column. 
When I try to insert it is not allowing me to insert sysing that Identity column should not be provided in the query while saving data. But I am unable to ignore the that column while insert the Data. 

Paulo Santos

unread,
Oct 13, 2023, 3:49:14 PM10/13/23
to nhusers
I have a similar problem.

However, in my case, the generator try to use a sequence that does not exit: “hibernate_sequence”.

This is the offending code:

    [Class(Table= "\"MyTable\"")]
    public class MyClass
    {
        [Id(Column = "id", TypeType = typeof(int))]
        [Generator(Class = "identity")]
        public virtual int Id { get; set; }
        // ....
    }

When I try to save an instance of this class I get the following Exception:

NHibernate.Exceptions.GenericADOException: could not insert: [URLShortener.Model.ShortUrlModel][SQL: INSERT INTO "ShortUrls" (id, ... ) VALUES (nextval ('hibernate_sequence'), ... ) returning id]
 ---> Npgsql.PostgresException (0x80004005): 42P01: relation "hibernate_sequence" does not exist

Because I'm using NHibernate.Mapping.Attributes, I use the “Generator” attribute. However, I have no way of defining the name of the sequence used.

Paulo Santos

Paulo Santos

unread,
Oct 14, 2023, 3:15:36 PM10/14/23
to nhusers
I'm writing here for posterity.

After going to the freaking source code of NHibernate, I finally figured it out.

In order for it to work correctly, one needs to do (for a PostgreSQL database -- I still need to check for SQL Server):

    [Class(Table= "\"MyTable\"")]
    public class MyClass
    {
        [Id(Column = "id", TypeType = typeof(int))]
        [Generator(Class = "sequence")]
        [Param(Name = "sequence", Content = "the_name_of_the_sequence")]

        public virtual int Id { get; set; }
        // ....
    }

Honestly, I don't remember having seen this part in the NHibernate.Mapping.Attributes documentation. I might have missed, though.
Reply all
Reply to author
Forward
0 new messages