C#:
ASP.NET / HTML:
JavaScript:
This theme is available for download.
public interface IRepository<T> { T Get(object id); void Save(T value>); void Update(T value); void Delete(T value); IList<T> GetAll(); }Note: The strength of this interface is its simplicity. Its Achilles' heel is that lazyloading will have to be disabled in order to reference associated objects. If this is a deal-breaker for you, check out the Unit of Work facade.
public class Monkey { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual bool FlingsPoo { get; set; } public virtual IList<Banana> Bananas { get; set; } } public class Banana { public virtual int Id { get; set; } public virtual string Color { get; set; } }NHibernate uses "mappings" to tie the classes to the database, and while it's possible to fulfill this example using FluentNHibernate auto mapping, most people prefer the control of the classic Fluent mapping classes, so that's what we'll use.
public class MonkeyMap : ClassMap<Monkey> { public MonkeyMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.FlingsPoo); HasMany<Banana>(x => x.Bananas) .Not.LazyLoad(); } } public class BananaMap : ClassMap<Banana> { public BananaMap() { Id(x => x.Id); Map(x => x.Color); } }That should take care of the database mapping. And now for the meat and potatoes:
public class NHibernateRepository<T> : IRepository<T> where T : class { protected Configuration config; protected ISessionFactory sessionFactory; public NHibernateRepository() { config = Fluently.Configure() .Database( MsSqlConfiguration .MsSql2008 .ConnectionString(@"Data Source=SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True")) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateRepository<T>>()) .BuildConfiguration(); sessionFactory = config.BuildSessionFactory(); } public void Save(T value) { using (var session = sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { session.Save(value); transaction.Commit(); } } }That's really all there is to it. I leave Get/Update/Delete/GetAll out as an exercise for the reader to implement (Hint: they're almost exactly like Save). Change the connection string to point at your test database and we should be good to go. What are we waiting for? Let's put a monkey in the database!
Monkey m = new Monkey() { Name = "George", FlingsPoo = true }; IRepository<Monkey> mRepo = new NHibernateRepository<Monkey>(); mRepo.Save(m);I think this is enough for one blog post. The complete compilable project based off of this example can be found at the Google Code project nhibernate-repository-example.
public interface IRepository<T> { T Get(object id); void Save(T value); void Update(T value); void Delete(T value); IList<T> GetAll(); }