Skip to content

Instantly share code, notes, and snippets.

@julian-maughan
Created December 19, 2012 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julian-maughan/4334576 to your computer and use it in GitHub Desktop.
Save julian-maughan/4334576 to your computer and use it in GitHub Desktop.
NHibernate Hello World (View associated the blog post here: http://julian.maughan.id.au/2012/12/hello-world-of-nhibernate-world.html)
using System;
namespace NHibernateHelloWorld
{
public class Customer
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
}
using System;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;
namespace NHibernateHelloWorld
{
/// <summary>
/// NHibernate Hello World - with by-code configuration and mappings
/// </summary>
/// <remarks>
/// Dependencies:
/// - Add NHibernate to your project using NuGet, i.e. 'Install-Package NHibernate'
/// - Update the connection string and dialect/driver for your database, as required
/// </remarks>
class Program
{
static void Main()
{
// Configure NHibernate
var configuration = new Configuration();
configuration.SessionFactory()
.Integrate.Using<MsSql2008Dialect>()
.Connected.Using("Server=localhost;Database=nhibernate;Integrated Security=SSPI");
// Mappings
var mapper = new ModelMapper();
mapper.Class<Customer>(rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Guid));
rc.Property(x => x.Name);
});
// Add mappings to configuration
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
configuration.AddMapping(mapping);
// Export schema - i.e. create the Customer table
new SchemaExport(configuration).Create(false, true);
// Use NHibernate
using (var sessionFactory = configuration.BuildSessionFactory())
{
// Persist a customer entity
using (var session = sessionFactory.OpenSession())
{
var customer = new Customer { Name = "Aristotle" };
session.SaveOrUpdate(customer);
session.Flush();
}
}
Console.ReadLine();
// Drop schema - i.e. drop the Customer table
new SchemaExport(configuration).Drop(false, true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment