0
votes

I'm trying to figure out how NHibernate is assigning ids to my game project that I inherited from a previous developer.

When a new photo is uploaded from the web, the API performs this action:

children.Add(e);
return Session.Save(e);
  • where children = array of photo objects{id, title, size}
  • where e = new photo object being uploaded and added to the array of children

Session is an NHibernate session.

There is a database table for the photos for with columns of id, title, and size.

The id column uses a sequence in sys.sequences for the ids, it is not an identity column. The name of the sequence is: nextGamePhotoId

When I run Visual Studio in debug mode and step through each process, I see this:

  • Before the Session.Save() call, the new photo object, e, has an id of zero.

  • After the Session.Save() call, e has a new id that is equal to the current_value + 1 from the sys.sequences table.

Despite running through my debugger, I can't figure out how or where NHibernate assigns the "id".

The photo class is mapped using NHibernate.Mapping.ByCode , like this:

 public class GamePhotoMapping : ClassMapping<GamePhoto>
    {
        public GamePhotoMapping()
        {
            Schema("game");
            this.EnhancedSequenceId(x => x.Id, "nextGamePhotoId");
            Property(x => x.Title, gp => gp.NotNullable(true));
            Property(x => x.size);
        }
    }

This is the only place in the code where I see a reference to the sequence(nextGamePhotoId).

So I guess NHibernate is doing something behind the scenes?

Does anyone know how exactly is NHibernate getting and assigning the id?

Thanks!

1
EnhancedSequenceId does not appear to be an NHibernate function, so it could be an specific implementation, "nextGamePhotoId" could be a function in the database layer which generates the next id, but all of this are assumptions, more info about EnhancedSequenceId and the database engine would be helpful. - diegoe

1 Answers

1
votes

When the 'transient' instance is added to the NH session, via the Save() method, NH will allocate it an id based on the type's id generation strategy. I'm not sure of how an 'enhanced' sequence differs from the regular sequence, however, taking a look at these classes (SequenceGenerator, MsSql2012Dialect) suggests that it simply selects the next key from the appropriate database sequence:

public override string GetSequenceNextValString(string sequenceName)
{
    return "select " + GetSelectSequenceNextValString(sequenceName) + " as seq";
}

public override string GetSelectSequenceNextValString(string sequenceName)
{
    return "next value for " + sequenceName;
}