Saturday, February 2, 2013

NHibernate - Generate Id from seed table


Recently I came across a problem where I had to auto generate entity Id by using seed table of database. I was not allowed to keep auto generate at database level.  I was using NHibernate ORM.

Scenario:
I have a seed table.
   Table : Seed
   Columns :
            1.       TableName
            2.       LastId
      I have to use this table to create id for other tables. I was looking a better way to accomplish this.

Solution :
            1.       Create a seed generator class - NHibernate gives an interface IIdentifierGenerator which really helps lot. It gives a signature to use and pass id.


namespace SimpleNHibernateClient.ConsoleApplication
{
    using NHibernate.Id;

    /// <summary>
    /// Seed Generator
    /// </summary>
    public class SeedGenerator<T> : IIdentifierGenerator
    {
        public object Generate(NHibernate.Engine.ISessionImplementor session, object obj)
        {
            return 1;/* Take it from seed table corresponding T. */
        }
    }
}


          2.       Entity Class-This is a entity class to be saved into database.

namespace SimpleNHibernateClient.ConsoleApplication
{
    public class Student
    {
        public virtual int Id { getset; }
        public virtual string Name { getset; }
    }
}

         3.       Mapping Class-This is a mapping class to be used for mapping and calling seed generator.


namespace SimpleNHibernateClient.ConsoleApplication
{
    using FluentNHibernate.Mapping;

    public class StudentMap : ClassMap<Student>
    {
        public StudentMap()
        {
            Table("Student");
            Id(x => x.Id, "Id").GeneratedBy.Custom<SeedGenerator<Student>>();
            Map(x => x.Name, "Name");
        }
    }
}

Now it gets generated by Generate Method.