How do I get the NextVal from an oracle Sequence thru NHibernate

7.3k Views Asked by At

I am working on c# .net 4.0 and using NHibernate to talk with an Oracle DB. You would think something as simple as this is already addressed somewhere but sadly its not. I need the NextVal from an Oracle sequence. I do not need to insert it a database as part of an Id or Primary key. I just need to use the next val on the c# side.

Can somebody help me out with xml mapping and C# file(or a link) to achieve this.

Thanks.

Something like

int NextValueOfSequence = GetNextValueofSequence();

public int GetNextValueOfSequence()
{

// Access NHibernate to return the next value of the sequence.

}
4

There are 4 best solutions below

4
On BEST ANSWER

Mapping:

  <sql-query name="GetSequence" read-only="true">
    <return-scalar type="Int64"/>
    <![CDATA[
    SELECT SeqName.NEXTVAL from DUAL;
    ]]>
  </sql-query>

Code:

Int64 nextValue = session.GetNamedQuery("GetSequence").UniqueResult<System.Int64>();
0
On

This also does the trick.

 <your session variable>.CreateSQLQuery("select <your sequence>.NEXTVAL from dual").UniqueResult<Int64>();
0
On

There is a small correction in the mapping given by @Petr Kozelek

<sql-query name="GetSequence" read-only="true">
    <return-scalar column="NextNo" type="Int64"/>
    <![CDATA[
        SELECT SeqName.NEXTVAL as NextNo from DUAL
    ]]>
</sql-query>
0
On

With NH4 I use this DB agnostic ISession extension method (obviously DB must support sequences)

public static T GetSequenceNextValue<T>(this ISession session, string sequenceName) where T : struct
{
    var dialect = session.GetSessionImplementation().Factory.Dialect;
    var sqlQuery = dialect.GetSequenceNextValString(sequenceName);
    return session.CreateSQLQuery(sqlQuery).UniqueResult<T>();
}