Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Minimum NHibernate Code

Sometimes people complain that NHibernate is difficult. Although NHibernate offers a lot of options when compared with other O/RMs, I don’t fully agree with this. Just as an example, all that it takes to setup NHibernate and perform all the mappings, with conventions being applied is:

   1: var cfg = new Configuration()
   2: .DataBaseIntegration(x =>
   3: {
   4:     x.Dialect<MsSql2008Dialect>();
   5:     x.Driver<Sql2008ClientDriver>();
   6:     x.ConnectionStringName = "NHibernate";
   7:     x.SchemaAction = SchemaAutoAction.Create;
   8: });
   9:  
  10: var modelMapper = new ConventionModelMapper();
  11: modelMapper.IsEntity((x, y) => x.IsClass == true && x.IsSealed == false && x.Namespace == typeof(Program).Namespace);
  12: modelMapper.BeforeMapClass += (x, y, z) => z.Id(a => a.Generator(Generators.Identity));
  13:  
  14: var mappings = modelMapper.CompileMappingFor(typeof(Program).Assembly.GetTypes().Where(x => x.IsPublic && x.IsSealed == false));
  15:  
  16: cfg.AddMapping(mappings);
  17:  
  18: using (var sessionFactory = cfg.BuildSessionFactory())
  19: {
  20:     using (var session = sessionFactory.OpenSession())
  21:     {
  22:         //...
  23:     }
  24: }

This sets up the dialect, ADO.NET provider, connection string and key generation strategy and it creates the database from scratch. All the rest is left for conventions. No need to create any classes or whatever. Pretty slick, don’t you think? Winking smile

Comments

Den Harrison said:

Yeah, based on years or experience you have. There is no good documentation. It is based on .NET 2 and 3. It is clunky. It is hard to learn unless you know it already. NHiberante sucks. The terrible kind.

# February 12, 2014 1:02 PM

Ricardo Peres said:

Den:

That's why I do my best to talk about NHibernate and to explain how to use it.

# February 13, 2014 4:24 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)