Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

Minimum NHibernate Code

$
0
0

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


Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>