Book Image

NHibernate 2 Beginner's Guide

By : Aaron Cure
Book Image

NHibernate 2 Beginner's Guide

By: Aaron Cure

Overview of this book

<p>NHibernate is an open source object-relational mapper, or simply put, a way to retrieve data from your database into standard .NET objects. Quite often we spend hours designing the database, only to go back and re-design a mechanism to access that data and then optimize that mechanism. This book will save you time on your project, providing all the information along with concrete examples about the use and optimization of NHibernate.<br /><br />This book is an approachable, detailed introduction to the NHibernate object-relational mapper and how to integrate it with your .NET projects. If you're tired of writing stored procedures or maintaining inline SQL, this is the book for you.<br /><br />Connecting to a database to retrieve data is a major part of nearly every project, from websites to desktop applications to distributed applications. Using the techniques presented in this book, you can access data in your own database with little or no code.<br /><br />This book covers the use of NHibernate from a first glance at retrieving data and developing access layers to more advanced topics such as optimization and Security and Membership providers. It will show you how to connect to multiple databases and speed up your web applications using strong caching tools. We also discuss the use of third-party tools for code generation and other tricks to make your development smoother, quicker, and more effective.</p>
Table of Contents (19 chapters)
NHibernate 2
Credits
About the Author
About the Reviewers
Preface
Index

Data Access Object methods


We will need to create a Save() method to handle create and update operations, a Delete() method to handle deletions, and a few GetX() methods to retrieve data.

In order to implement the basic Save() and Delete() methods, we should do two things:

  • Insert the logic for the method

  • Wrap the method in a transaction

Why do we need to wrap it in a transaction? If something goes wrong and our action can't be completed, we can roll back the transaction and handle it in our code.

public int Save(Contact contact)
{
  ITransaction transaction = null;

  try
  {
    transaction = Session.BeginTransaction();
    Session.SaveOrUpdate(contact);

    transaction.Commit();
    return contact.Id;
  }
  catch (Exception ex)
  {
    log.Error(ex);
    if (transaction != null && transaction.IsActive)
      transaction.Rollback();
    throw;
  }
}

Adding our Save() method in VB.NET is just as trivial.

Public Function Save(ByVal contact As Contact) As System.Nullable(Of Integer)
  Dim...