NHibernate 2. Beginner's Guide. Rapidly retrieve data from your database into.net objects. Aaron B. Cure BIRMINGHAM - MUMBAI

Similar documents
Learning Drupal 6 Module Development

Learning JavaScript Data Structures and Algorithms

Software Testing using Visual Studio 2010

TortoiseSVN 1.7. Beginner's Guide. Perform version control in the easiest way with the best SVN client TortoiseSVN.

Foundation Flash MX Applications

Selenium Testing Tools Cookbook

Bruce Moore Fall 99 Internship September 23, 1999 Supervised by Dr. John P.

Blackboard Portfolio System Owner and Designer Reference

DotNetNuke Skinning Tutorial

Foreign-Key Associations

PHP 5 e-commerce Development

Microsoft. SharePoint Your Organization s Name Here

User Manual. SmartLite WebQuiz SQL Edition

SPRING MVC: BEGINNER'S GUIDE BY AMUTHAN G DOWNLOAD EBOOK : SPRING MVC: BEGINNER'S GUIDE BY AMUTHAN G PDF

MAPLOGIC CORPORATION. GIS Software Solutions. Getting Started. With MapLogic Layout Manager

Survey Creation Workflow These are the high level steps that are followed to successfully create and deploy a new survey:

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Oracle Business Intelligence: The Condensed Guide to Analysis and Reporting

Android SQLite Essentials

RealPresence Media Manager

MadCap Software. Index Guide. Flare 2017 r2

Book IX. Developing Applications Rapidly

BOLT eportfolio Student Guide

Campaign Walkthrough

Kindle Books InfoPath With SharePoint 2010 How-To

CHAPTER 1: GETTING STARTED WITH ASP.NET 4 1

Javelin Workbench Tutorial. Version 3.0 September, 2009

Exploring.Net Orcas. Contents. By Punit Ganshani

Learning and Development. UWE Staff Profiles (USP) User Guide

Working with Mailbox Manager

IBM TRIRIGA Application Platform Version 3 Release 4.2. Object Migration User Guide

Sql Server Working With Schemas Vs Database Role Membership

Advanced WCF 4.0 .NET. Web Services. Contents for.net Professionals. Learn new and stay updated. Design Patterns, OOPS Principles, WCF, WPF, MVC &LINQ

Getting Started with EPiServer 4

District 5910 Website Quick Start Manual Let s Roll Rotarians!

Professional Edition User Guide

--Microsoft-- --Windows Phone--

Product Documentation. ER/Studio Portal. User Guide. Version Published February 21, 2012

Atlassian Confluence 5 Essentials

What You Need to Use this Book

How & Why We Subnet Lab Workbook

Dreamweaver is a full-featured Web application

/smlcodes /smlcodes /smlcodes JIRA. Small Codes. Programming Simplified. A SmlCodes.Com Small presentation. In Association with Idleposts.

Beginning ASP.NET. 4.5 in C# Matthew MacDonald

Writing & Executing a Software Validation Protocol: Plain and Simple

Dreamweaver is a full-featured Web application

Revision History Overview Feature Summary Knowledge Management Policy Automation Platform Agent Browser Workspaces Agent Browser Desktop Automation

Head First C#, 2E: A Learner's Guide To Real-World Programming With Visual C# And.NET (Head First Guides) Free Ebooks PDF

Getting Started with EPiServer 4

WORDPRESS 101 A PRIMER JOHN WIEGAND

Hello, and welcome to another episode of. Getting the Most Out of IBM U2. This is Kenny Brunel, and

Birst Pronto: Connect to Data in Pronto

FileMaker, Inc. All Rights Reserved. Document Version 2.0 FileMaker, Inc Patrick Henry Drive Santa Clara, California FileMaker

10267A CS: Developing Web Applications Using Microsoft Visual Studio 2010

R EIN V E N TIN G B U S I N E S S I L E M A. MARK5 Basic guide. - All rights reserved

Workspace Administrator Help File

Who should use this manual. Signing into WordPress

Lesson 3 Transcript: Part 1 of 2 - Tools & Scripting

HTML5 Games Development by Example

Selenium Testing Tools Cookbook

An Easy to Understand Guide 21 CFR Part 11

Planning and Designing Your Site p. 109 Design Concepts p. 116 Summary p. 118 Defining Your Site p. 119 The Files Panel p. 119 Accessing Your Remote

Symantec Workflow Solution 7.1 MP1 Installation and Configuration Guide

Custom Functions User's Guide SAP Data Services 4.2 (14.2.0)

User Guide. Datgel. Photo Tool gint Add-In 3

Chapter 4: Single Table Form Lab

Building an ASP.NET Website

ASP.NET MVC 1.0 Quickly

MCAD/MCSD Self-Paced Training Kit: Developing Windows -Based Applications With Microsoft Visual BasicÂ.NET And Microsoft Visual C#Â.

DOT NET COURSE BROCHURE

MOODLE MANUAL TABLE OF CONTENTS

Web Development with Java

Microsoft Windows SharePoint Services

MARKETING VOL. 1

Relativity Designer 2.2

IOS 9 App Development Essentials: Learn To Develop IOS 9 Apps Using Xcode 7 And Swift 2 PDF

Getting Help...71 Getting help with ScreenSteps...72

Read & Download (PDF Kindle) XML For Dummies

Database Application Architectures

Steps To Create Approval Workflow In Sharepoint Designer 2007

Design and Implementation of File Sharing Server

Copyright. For more information, please read the Disclosures and Disclaimers section at the end of this ebook. First PDF Edition, February 2013

Oracle Financial Services Governance, Risk, and Compliance Workflow Manager User Guide. Release February 2016 E

Creating databases using SQL Server Management Studio Express

Teacher Guide. Edline -Teachers Guide Modified by Brevard Public Schools Revised 6/3/08

1. Download and install the Firefox Web browser if needed. 2. Open Firefox, go to zotero.org and click the big red Download button.

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

Persistence on Score Management of Japanese-Language Proficiency Test Based on NHibernate Fengjuan Liu

Setting Up A WordPress Blog

Customer Helpdesk User Manual

Kindle Books Microsoft SharePoint Designer 2010 Step By Step

Building Websites with the ASP.NET Community Starter Kit. K. Scott Allen Cristian Darie

Simple sets of data can be expressed in a simple table, much like a

facebook a guide to social networking for massage therapists

ADO.NET In A Nutshell Download Free (EPUB, PDF)

EMC Documentum Forms Builder

eprocurement Web Site

In Figure 6, users can view their profile information in the Profile tab displayed by. Figure 8 Figure 7

ClientBase. Windows. FUNctionality

HTML5 Responsive Notify 2 DMXzone

Transcription:

NHibernate 2 Beginner's Guide Rapidly retrieve data from your database into.net objects Aaron B. Cure BIRMINGHAM - MUMBAI

NHibernate 2 Beginner's Guide Copyright 2010 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: May 2010 Production Reference: 1050510 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847198-90-7 www.packtpub.com Cover Image by Louise Barr (lou@frogboxdesign.co.uk)

Table of Contents Preface 1 Chapter 1: First Look 7 What is NHibernate? 8 Why would I use it? 8 Where do I get it? 8 Can I get help using NHibernate? 9 Database table 9 The XML mapping file (hbm.xml) 10 Plain Old CLR Object ( POCO ) 11 Data access 11 Look how easy it is to use! 12 Summary 14 Chapter 2: Database Layout and Design 15 Before you get started 15 Laying the foundation table layouts 16 Time for action creating an ordering system database 16 Table layouts 19 NHibernate assigned IDs 20 Relationships 21 Normal Form 25 Putting it all together 26 Time for action adding some tables to our Ordering system database 26 Summary 35 Chapter 3: A Touch of Class 37 Start up our applications 37 Creating objects 37 Time for action creating our first class 38 Public properties and private variables 45

Table of Contents Time for action adding a few properties 46 Converting SQL database types to.net types 50 Properties for Foreign Keys 51 Summary 54 Chapter 4: Data Cartography 55 What is mapping? 55 Types of mapping 56 XML mapping 56 Getting started 57 Classes 57 Properties 58 ID columns 59 Mapping our types 60 Time for action mapping basic types 60 Relationships 72 One-to-many relationships 72 Many-to-many relationships 74 Getting started 76 Time for action mapping relationships 77 Fluent mapping 79 Summary 82 Chapter 5: The Session Procession 83 What is an NHibernate session? 83 Time for action getting ready 84 What is a session factory? 93 Creating your first session 94 Why do we call.commit()? 95 NHibernate session versus database session? 96 Time for action creating a session and doing some CRUD 96 Sessions in ASP.NET 102 Summary 104 Chapter 6: I'm a Logger 105 Why do we need to log? 105 Why log4net? 106 Getting started 107 Configuration 108 Time for action adding some logging 110 NHibernate log messages 113 Appenders 115 [ ii ]

Table of Contents Creating a logger 118 Time for action adding some custom logging 120 Summary 123 Chapter 7: Configuration 125 Looking back 125 The basics of configuration 126 Taking a look at the SQL 129 Abstracting the configuration 130 Time for action moving our configuration 132 XML configuration 135 Summary 136 Chapter 8: Writing Queries 137 Using Data Access Objects 137 The basic Data Access Object 138 Time for action creating our basic Data Access Object 139 Data Access Object methods 143 Time for action adding some CRUD methods 146 Coding some GetX() methods 149 The FieldNames structure 150 Time for action expanding our capabilities 152 The ICriteria object 154 Creating a GetAll() method 155 Paging and Sorting GetAll() methods 157 Filtering ICriteria 159 Time for action replacing our inline code 161 Summary 162 Chapter 9: Binding Data 163 Why should we use data binding? 164 Time for action adding an ASP.NET project 164 Basic data binding techniques 170 Common data binding methods 173 A simple templated control 176 Creating a control instance 177 The <asp:listview> control 179 The <asp:objectdatasource> control 180 Time for action adding our first data bound control 182 Direct data binding 188 One last control the <asp:formview> 190 Summary 195 [ iii ]

Table of Contents Chapter 10:.NET Security 197 Built-in controls 197 Time for action adding a login to our page 200 Membership providers 201 Location security 202 Configuring our provider 204 Time for action create a membership provider 205 User roles 209 Role providers 210 Provider configuration 210 Summary 212 Chapter 11: It's a Generation Thing 213 Judging requirements 214 CodeSmith 215 nhib-gen 217 AjGenesis 218 Visual NHibernate 221 MyGeneration 221 Time for action using MyGeneration 223 NGen NHibernate Code Generator 227 NHModeller 228 Microsoft T4 templates 232 T4 hbm2net 232 Summary 233 Chapter 12: Odds and Ends 235 Unit of Work and Burrow 235 How does this relate to NHibernate? 237 Blog.Net blogging components 237 maxrequestlength 237 Converting CSS templates 238 Time for action converting a CSS template 239 XML documentation & GhostDoc 246 Summary 248 Appendix: Pop Quiz Answers 249 Chapter 2 Database Layout and Design 249 Relationships 249 Chapter 3 A Touch of Class 249 Mapping 249 Chapter 4 Data Cartography 250 Class mapping 250 [ iv ]

Table of Contents Chapter 5 The Session Procession 250 Creating and updating records 250 Chapter 6 I'm Logger 250 Logging 250 Chapter 7 Configuration 251 Basic configuration 251 Chapter 8 Writing Queries 251 Fieldnames and ICriteria 251 Chapter 9 Binding Data 251 Basic data binding 251 Chapter 10.NET Security 252 Access configuration 252 Chapter 12 Odds and Ends 252 Burrowing in 252 Index 253 [ v ]

Preface NHibernate is a popular, fast growing Object-Relational Mapper (ORM) with a helpful community of seasoned developers. It is used in thousands of commercial and open source projects. Armed with a set of simple (and mostly free) tools and the knowledge you'll gain from this book, you can quickly and easily create an entire data-bound website, desktop application, windows or web service, or virtually any other.net project you can conceive. What this book covers Chapter 1, First Look, discusses what an object-relational mapper is, what NHibernate is, and the features it provides us. Chapter 2, Database Layout and Design, discusses how your database is constructed, how the data is related, and how to optimize it for the best performance using NHibernate. Chapter 3, A Touch of Class, explains how creating classes to represent your data makes it easy for you to work with the data and allows you to branch from the design of the database, if need be. Chapter 4, Data Cartography, deals with the actual interface to the database with NHibernate, either using XML mapping files, Fluent NHibernate, or no mapping at all. We also talk about lazy loading, using a fieldnames structure to help avoid typos, and generating the database from our mapping files or classes. Chapter 5, The Session Procession, teaches you how to create NHibernate sessions, which use database sessions to retrieve and store data into the database. Chapter 6, I'm a Logger, teaches you how to use the log4net logging framework for creating our own logs and tap into the information provided by NHibernate (including SQL statements) to monitor and troubleshoot our application.

Preface Chapter 7, Configuration, explains how to configure our application so, we are ready to retrieve and store data into our database. Additional configuration options are discussed, as well as optional configuration properties for particular situations. Chapter 8, Writing Queries, discusses using NHibernate to actually retrieve data, to include individual records and collections of records. We talk about filtering records and using the fieldnames structure we created earlier to speed up our development. We also talk about adding parameters to make paging and sorting work in data-bound controls. Chapter 9, Binding Data, explains how to use the data methods we created earlier to build a web application that uses our data access layer, the ObjectDataSource, and other data controls to retrieve, display, and even insert/update database data. Chapter 10, NET Security Providers, presents information about controlling access to and restricting the usage of data within a.net web application. We discuss the use of custom membership and role providers with NHibernate to control access to information. Chapter 11, It's a Generation Thing, discusses how to use code generation techniques such as CodeSmith, NHib-Gen, and MyGeneration to automatically generate our data access layer to get us up and running that much quicker. Chapter 12, Odds and Ends, discusses some advanced topics such as the Burrow session management framework and the NHibernate SchemaExport tool. What you need for this book To successfully complete the examples in this book, you will need a copy of either Visual Studio 2008 or 2010. You can use any version as long as it includes the web application projects. This could be either a Visual Web Developer Express version or any full version such as Professional. In addition to Visual Studio, you will also need a SQL database server. The examples are generated using SQL Server Express 2008 and SQL Server Management Studio (SSMS) Express. You will also need to download the NHibernate binary files from sourceforge.net. Who this book is for This book is for new and seasoned developers of.net web or desktop applications who want a better way to access database data. It is a basic introduction to NHibernate, with enough information to get a solid foundation in using NHibernate. Some advanced concepts are presented where appropriate to enhance functionality or in situations where they are commonly used. [ 2 ]

Preface Conventions In this book, you will find several headings appearing frequently. To give clear instructions on how to complete a procedure or task, we use: Time for action heading 1. Action 1 2. Action 2 3. Action 3 Instructions often need some extra explanation so that they make sense, so they are followed with: What just happened? This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including: Pop quiz heading These are short multiple choice questions intended to help you test your own understanding. Have a go hero heading These set practical challenges and give you ideas for experimenting with what you have learned. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "This will give us a new DLL project called Ordering.Data inside a folder named Ordering, which contains a solution named Ordering." [ ]

Preface A block of code is set as follows: using System; using System.Collections.Generic; using System.Text; namespace Ordering.Data { class OrderHeader { } } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: public class OrderHeader { public OrderHeader() { } } Any command-line input or output is written as follows: 07:18:08.295 [10] INFO NHibernate.Cfg.Configuration - Mapping resource: Ordering.Data.Mapping.Address.hbm.xml New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: Right-click on the Ordering. Console application, and select Add New Item. Warnings or important notes appear in a box like this. Tips and tricks appear like this. [ ]

Preface Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code for the book Visit https://www.packtpub.com//sites/default/files/ downloads/8907_code.zip to directly download the example code. The downloadable files contain instructions on how to use them. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books maybe a mistake in the text or the code we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. [ ]

Preface Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. [ ]

1 First Look It seems like every single project we begin as developers, no matter how simple, requires some sort of storage. Sometimes this is a simple collection of values in an XML file or a key-value pair in a properties file. However, more often, we need to have access to larger volumes of data, represented in multiple related database tables. In either case, we are generally forced to reinvent the wheel, to create new data retrieval and storage methods for each piece of data we want to access. Enter NHibernate. In this chapter, we will discuss: What NHibernate is and why we should use it HBM mapping files Plain Old CLR Objects (POCOs) Data access classes A simple web page databound to a collection of NHibernate objects

First Look What is NHibernate? That's a great question, and I'm glad you asked! NHibernate is an open source persistence layer based on Object-Relational Mapping Techniques or simply a tool that creates a "virtual representation" of database objects within the code. According to the creators of NHibernate: NHibernate is a port of Hibernate Core for Java to the.net Framework. It handles persisting plain.net objects to and from an underlying relational database. Given an XML description of your entities and relationships, NHibernate automatically generates SQL for loading and storing the objects. In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead of writing reams of SQL statements or creating stored procedures that "live" in a different place than our code, we can have all of our data access logic contained within our application. With a few simple "tricks" that we'll discuss in Chapter 4, Data Cartography, not only will our queries be effective, but they will also be validated by the compiler. Therefore, if our underlying table structure changes, the compiler will alert us that we need to change our queries! Why would I use it? Unless you love to write CRUD (Create, Retrieve, Update, Delete) methods over and over for each of the pieces of data you need to access (and I don't know a single developer who does), you are probably looking for a better method. If you're like me, then you know how to lay down an elegant database design (and if you don't, take a peek at Chapter 2, Database Layout and Design). Once the database is ready, you just want to use it! Wouldn't it be nice to create a few tables, and in just a few minutes, have a working set of forms that you can use for all of your basic CRUD operations, as well as a full set of queries to access the most common types of data? We'll discuss some of the ways to automatically generate your NHibernate data files in Chapter 11, It's a Generation Thing. Where do I get it? The home of the NHibernate project is at http://www.nhforge.org, while the code is housed at SourceForge (http://sourceforge.net/projects/nhibernate/). If you download the latest GA (Generally Available, also known as final or stable) bin release (binaries only, no source code) of the NHibernate project, you will have everything you need to get started. As of this writing, the current release is NHibernate-2.1.2.GA-bin, and all of the examples have been developed using this version. This version is available at http://downloads.sourceforge.net/project/nhibernate/nhibernate/ 2.1.2GA/NHibernate-2.1.2.GA-bin.zip. [ ]

Can I get help using NHibernate? Chapter 1 There is a great community site for NHibernate on the Web called the NHibernate Forge. It is located at http://www.nhforge.org/, and it provides a wealth of resources for the new and veteran NHibernate user. Have a go hero looking at some sample files A basic NHibernate project is composed of three major parts. You will need a mapping file to tell NHibernate how the database is or should be (see the Mapping our types section in Chapter 4) constructed, some data access methods to tell NHibernate what data you want to retrieve or store into the database, and a POCO to allow you to interact with the data. While XML mapping files are commonly used in NHibernate projects, they are not the only way to map data to POCOs (more in Chapter 4). Take a look at some sample files, but don't get too hung up on them. We'll go into more detail in the later chapters. Database table The first item we need to use NHibernate is a database table to map against. In the following screenshot, we define a table named Login with a Primary Key column named Id, two nullable fields to store the FirstName and LastName, and two non-nullable fields to store the UserName and Password. [ ]

First Look The XML mapping file (hbm.xml) The following code snippet shows the Login.hbm.xml mapping file for this simple table, with all the information required not only to map the data, but also to create the database from the metadata contained within the mapping file. If we do not want to be able to generate the database from the mapping file, then we can omit all of the sql-type, unique, and index properties. Some immediate information you might pick up from the file are the name of the class that NHibernate will use to map database rows (BasicWebApplication.Common. DataObjects.Login), which is defined in the <class> tag. This says that the BasicWebApplication.Common.DataObjects.Login object is contained in the BasicWebApplication assembly. It further defines that the Login table is the database table we will be mapping to, using the <table> element. There is an <id> tag that defines what the unique identifier (ID) is for the database record, as well as how that identifier is expected to be created. In our case, the <generator class="hilo"> tag specifies that we will be using the hi/lo Persistent Object ID (POID) generator for IDs. The four string fields FirstName, LastName, UserName, and Password are then mapped to the four database columns of the same names, using the <property> tag. <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="basicwebapplication.common.dataobjects" assembly="basicwebapplication"> <class name="login" table="login"> <id name="id" type="int32" unsaved-value="null"> <column name="id" /> <generator class="hilo" /> </id> <property name="firstname" type="string" /> <property name="lastname" type="string" /> <property name="username" type="string" /> <property name="password" type="string" /> </class> </hibernate-mapping> [ 10 ]

Plain Old CLR Object ( POCO ) Chapter 1 The Login.cs class shown in the following code snippet is the POCO, the class that NHibernate will use to map database rows. Each row in the database returned will be instantiated (also known as "newed up") in a new instance of the Login class. The collection of rows will be returned as a generic IList of Login objects or an IList<Login>. Notice how each property in the class Login maps directly to a property element in the hbm.xml file. We really have five public properties on this object, Id, FirstName, LastName, UserName, and Password. Each of these properties was defined earlier in the hbm.xml file and mapped to a database field. When NHibernate retrieves records from the database, it will create a new instance (also known as "new up") of a Login object for each record it retrieves and use the public "setter" (set function) for each property to fill out the object. public partial class Login { public Login() { } } public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string UserName { get; set; } public virtual string Password { get; set; } Data access The final class, LoginDataControl.cs, provides CRUD methods for data retrieval, storage, and removal. The session variable is an NHibernate session (you can find out more about session management in Chapter 5, The Session Procession). This class defines a few simple CRUD methods that are used quite often when manipulating database records. The GetById(int id) function allows the user to pass in an integer and retrieve the record with that ID. The GetAll() method returns all of the records in a given table. GetCountOfAll() returns a count of the records in the table, while allowing controls that handle pagination and record navigation to function. public class LoginDataControl { public LoginDataControl() { } ISession session; [ 11 ]

First Look } public Login GetById(int id) { Login retval = session.get<login>(id); return retval; } public IList<Login> GetAll() { ICriteria criteria = session.createcriteria<login>(); IList<Login> retval = criteria.list<login>(); return retval; } public int GetCountOfAll() { return GetAll().Count; } Look how easy it is to use! The sample Login.aspx ASP.NET file shows one of the best reasons why we use NHibernate. By using an ObjectDataSource, we can map the NHibernate objects directly to the data-bound controls that will display or interact with them. All we have to do is create an ObjectDataSource to retrieve the data from our data access class (LoginDataControl.cs), create a set of form fields to display the data (like the <asp:gridview> "LoginGrid" below), and let ASP.NET handle all of the tedious work for us. By the way, this page will work exactly as shown there is no page logic in the code behind or anywhere else. All we have in this code is a GridView to present the information and an ObjectDataSource to interact with our DataAccess classes and provide data for the GridView. The GridView has BoundField definitions for all of the fields in our database table as well as Sorting and Paging functions. The ObjectDataSource has methods mapped for Select, Select Count, Insert, and Update. When the GridView needs to perform one of these functions, it relies on the ObjectDataSource to handle these operations. Working in tandem, these two controls (as well as nearly any other data bound control) can provide a very quick and simple interface for your data! <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BasicWebApplication.Web._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> [ 12 ]