Created
December 19, 2012 05:24
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace NHibernateHelloWorld | |
{ | |
public class Customer | |
{ | |
public virtual Guid Id { get; set; } | |
public virtual string Name { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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