NHibernate 3.2 Mapping by Code – Basic Mapping

27 Sep 2011 by

NHibernate 3.2 is coming with default mapping interface that based on ConfORM interface NOT Fluent NHibernate interface. Since its released, there is little document on how to manage mapping by code with this new interface. So this post will contribute to the short.

I have a simple schema as follow:

I have these files to show you.

  1. App.Config, configuration file
  2. ApplicationContext.cs, manage NHibernate configuration and SessionFactory
  3. Province.cs, District.cs, a domain model as depicted in the figure above
  4. ProvinceMap.cs, DistrictMap.cs, a class-by-class mapping
  5. SchemaTest.cs, a drop and create schema for testing
  6. A full source code will be uploaded later while tutorial is completed
App.Config


  
    
  
  
    
  

ApplicaionContext.cs
  public class ApplicationContext
  {
    public static Configuration NHConfiguration { get; set; }
    public static ISessionFactory SessionFactory { get; set; }

    public static void AppConfigure()
    {
      #region NHibernate configuration

      NHConfiguration = ConfigureNHibernate();

      SessionFactory = NHConfiguration.BuildSessionFactory();

      #endregion
    }

    private static Configuration ConfigureNHibernate()
    {
      var configure = new Configuration();
      configure.SessionFactoryName("BuildIt");

      configure.DataBaseIntegration(db =>
      {
        db.Dialect();
        db.Driver();
        db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
        db.IsolationLevel = IsolationLevel.ReadCommitted;

        db.ConnectionStringName = "NH3";
        db.Timeout = 10;

        // enabled for testing
        db.LogFormattedSql = true;
        db.LogSqlInConsole = true;
        db.AutoCommentSql = true;
      });

      var mapping = GetMappings();
      configure.AddDeserializedMapping(mapping, "NHSchemaTest");
      SchemaMetadataUpdater.QuoteTableAndColumns(configure);

      return configure;
    }

    private static HbmMapping GetMappings()
    {
      var mapper = new ModelMapper();

      mapper.AddMappings(Assembly.GetAssembly(typeof(ProvinceMap)).GetExportedTypes());
      var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

      return mapping;
    }
  }
Province.cs
  public class Province
  {
    public Province()
    {
      Districts = new List();
    }

    public virtual long Id { get; set; }
    public virtual string Code { get; set; }
    public virtual string Name { get; set; }
    public virtual IList Districts { get; set; }
  }
District.cs
  public class District
  {
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Province Province { get; set; }
  }
ProvinceMap.cs
  public class ProvinceMap : ClassMapping
  {
    public ProvinceMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p => p.Code, map =>
                              {
                                map.Length(3);
                                map.NotNullable(true);
                              });
      Property(p=>p.Name);

      Bag(p => p.Districts, map => map.Key(k => k.Column("ProvinceId")), ce => ce.OneToMany());
    }
  }
DistrictMap.cs
  public class DistrictMap : ClassMapping
  {
    public DistrictMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p=>p.Name);
      ManyToOne(p=>p.Province, map=>map.Column("ProvinceId"));
    }
  }
SchemaTest.cs
  public class SchemaTest
  {
    [Test, Explicit]
    public void Create()
    {
      ApplicationContext.AppConfigure();
      new SchemaExport(ApplicationContext.NHConfiguration).Create(false, true);
    }

    [Test, Explicit]
    public void Drop()
    {
      ApplicationContext.AppConfigure();
      new SchemaExport(ApplicationContext.NHConfiguration).Drop(false, true);
    }
  }

5 responses so far

  • Wiebe says:

    Dude, I wish I had ran across this site sooner. I bet a lot of people are trying to figure stuff out as they upgrade from fluent nhibernate to nhibernate 3.x. Kudos!

  • awatarr says:

    Very good tutorial. Wish I had found it sooner. Great job

  • sgt says:

    Thank you

  • Adam says:

    Hi there,

    Just using your example to ‘fill in the gaps’ on a NHibernate (with Fluent emphasis) tutorial. I’m told mapping by code is the better way to go, but then NHibernate tutorials in Mapping flavour are hard to track down!

    So putting your code into action on my project, I get this error when ReSharper checks Province.cs :

    Virtual member call in constructor

    On this line here :

    >>> Districts = new List();

    All code is identical to yours.

    Could you tell me why this is ?

    Many thanks!

    Adam

Leave a Reply