NHibernate 2 - Cure Aaron B. - E-Book

NHibernate 2 E-Book

Cure Aaron B.

0,0
23,50 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

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.

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.

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.

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.

This easy-to-follow guide will show you how to connect the NHibernate object-relational mapper to your projects to create a rich, efficient, object-oriented data access layer with little or no additional work

Approach

This is a beginner's guide to NHibernate that starts from ground zero. Successive chapters build upon earlier concepts, while the sample code presents various ways to accomplish typical data access tasks. Within a few chapters you have a running application using NHibernate to retrieve and store data.

We examine all of the topics required to get a functional data access layer implemented by writing the least amount of code possible, presenting options along the way to handle particular edge cases or situations as they arise.

When you have completed the various exercises you will have running data-bound desktop and web applications, as well as an understanding of how to implement NHibernate in your own applications.

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.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 254

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

NHibernate 2
Credits
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Time for action – heading
What just happened?
Pop quiz – heading
Have a go hero – heading
Reader feedback
Customer support
Errata
Piracy
Questions
1. First Look
What is NHibernate?
Why would I use it?
Where do I get it?
Can I get help using NHibernate?
Have a go hero – looking at some sample files
Database table
The XML mapping file (hbm.xml)
Plain Old CLR Object ( POCO )
Data access
Look how easy it is to use!
Summary
2. Database Layout and Design
Before you get started
Laying the foundation—table layouts
Time for action – creating an ordering system database
What just happened?
Table layouts
NHibernate assigned IDs
Relationships
Pop quiz – relationships
Normal Form
Have a go hero – looking back
Putting it all together
Time for action – adding some tables to our Ordering system database
What just happened?
Have a go hero – create some more tables
Summary
3. A Touch of Class
Start up our applications
Creating objects
Time for action – creating our first class
What just happened?
Have a go hero – ramping up
Public properties and private variables
Time for action – adding a few properties
What just happened?
Converting SQL database types to .NET types
Properties for Foreign Keys
Have a go hero – adding more properties (and classes!)
Pop quiz – mapping
Summary
4. Data Cartography
What is mapping?
Types of mapping
XML mapping
Getting started
Classes
Properties
ID columns
Mapping our types
Time for action – mapping basic types
What just happened?
Pop quiz – class mapping
Relationships
One-to-many relationships
Many-to-many relationships
Getting started
Time for action – mapping relationships
What just happened?
Have a go hero – flushing out the rest of our map
Fluent mapping
Pop quiz – fluent mapping
Summary
5. The Session Procession
What is an NHibernate session?
Time for action – getting ready
What just happened?
What is a session factory?
Creating your first session
Why do we call .Commit()?
NHibernate session versus database session?
Time for action – creating a session and doing some CRUD
Pop quiz – creating and updating records
Have a go hero – creating a full order
Sessions in ASP.NET
Summary
6. I'm a Logger
Why do we need to log?
Why log4net?
Getting started
Have a go hero – adding some logging
Configuration
Time for action – adding some logging
What just happened?
NHibernate log messages
Appenders
Pop quiz – creating and updating records
Creating a logger
Time for action – adding some custom logging
What just happened?
Have a go hero – adding some logging
Summary
7. Configuration
Looking back
The basics of configuration
Pop quiz – basic configuration
Taking a look at the SQL
Have a go hero – using the connection string name
Abstracting the configuration
Time for action – moving our configuration
What just happened?
XML configuration
Have a go hero – using an XML configuration file
Summary
8. Writing Queries
Using Data Access Objects
The basic Data Access Object
Time for action – creating our basic Data Access Object
What just happened?
Data Access Object methods
Time for action – adding some CRUD methods
What just happened?
Coding some GetX() methods
The FieldNames structure
Time for action – expanding our capabilities
What just happened?
The ICriteria object
Pop quiz – FieldNames and ICriteria
Creating a GetAll() method
Paging and Sorting GetAll() methods
Have a go hero – creating some paging and sorting methods
Filtering ICriteria
Time for action – replacing our inline code
What just happened?
Summary
9. Binding Data
Why should we use data binding?
Time for action – adding an ASP.NET project
What just happened?
Basic data binding techniques
Common data binding methods
A simple templated control
Pop quiz – basic data binding
Creating a control instance
The <asp:ListView> control
The <asp:ObjectDataSource> control
Time for action – adding our first data bound control
What just happened?
Direct data binding
Have a go hero – give direct data binding a try
One last control—the <asp:FormView>
Have a go hero – creating an <asp:FormView>
Summary
10. .NET Security
Built-in controls
Time for action – adding a login to our page
What just happened?
Membership providers
Location security
Pop quiz – doing the thing
Configuring our provider
Time for action – create a membership provider
What just happened?
User roles
Role providers
Provider configuration
Have a go hero – using some roles
Summary
11. It's a Generation Thing
Judging requirements
CodeSmith
nhib-gen
AjGenesis
Visual NHibernate
MyGeneration
Time for action – using MyGeneration
What just happened?
NGen NHibernate Code Generator
NHModeller
Microsoft T4 templates
T4 hbm2net
Summary
12. Odds and Ends
Unit of Work and Burrow
Pop quiz – doing the thing
How does this relate to NHibernate?
Blog.Net blogging components
maxRequestLength
Converting CSS templates
Time for action – converting a CSS template
What just happened?
Have a go hero – .NETing the master page
XML documentation & GhostDoc
Summary
A. Pop Quiz Answers
Chapter 2 – Database Layout and Design
Relationships
Chapter 3 – A Touch of Class
Mapping
Chapter 4 – Data Cartography
Class mapping
Chapter 5 – The Session Procession
Creating and updating records
Chapter 6 – I'm Logger
Logging
Chapter 7 – Configuration
Basic configuration
Chapter 8 – Writing Queries
Fieldnames and ICriteria
Chapter 9 – Binding Data
Basic data binding
Chapter 10 – .NET Security
Access configuration
Chapter 12 – Odds and Ends
Burrowing in
Index

NHibernate 2

Beginner's Guide

Aaron Cure

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 (<[email protected]>)

Credits

Author

Aaron B. Cure

Reviewers

Jason Dentler

Fabio Maulo

Acquisition Editor

Usha Iyer

Development Editor

Chaitanya Apte

Technical Editor

Ajay B. Chamkeri

Copy Editor

Leonard D'Silva

Indexer

Monica Ajmera Mehta

Editorial Team Leader

Aanchal Kumar

Project Team Leader

Priya Mukerji

Project Coordinator

Ashwin Shetty

Proofreader

Lynda Sliwoski

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Aaron Cure is an avid developer, instructor, and innovator. During his 10 years in the military as a linguist and a satellite communications repair technician, he learned that his real love was computer programming.

After various throes with PHP, Classic ASP, VB, and a brief encounter with Java/JSP, he found a real passion for the .NET framework. After searching for a "better way" to carry out database storage and retrieval, Aaron stumbled across the NHibernate framework.

Unsatisfied with the options for interacting with this great framework, he founded the NHibernate Generation project (nhib-gen) on SourceForge to reduce the "barrier to entry" for most developers.

Aaron and his family run a small consulting and web hosting company doing web design and custom software development for various organizations across the country. One of their more interesting projects has been software to control laser cutting machines.

In his spare time, he also enjoys developing projects with his daughters, using everything from Lego NXT (using C# and Bluetooth communications) to the Microchip PIC platform (using JAL and USB). He also collects and restores classic farm tractors, engines, and farm equipment as well as semi trucks and trailers. He and his family display them at tractor shows, parades, schools, and various other community events.

This book is dedicated to my beautiful and talented wife, Sherry, and my two wonderful daughters, Kaitlyn and MacKenzie. Without their love and support, this book would have never been written.

I would also like to thank my parents, Karen and Chuck, as I wouldn't be here without them.

Special thanks to my editors at Packt Publishing, who had more patience with me than I think I would have had and stuck with me throughout.

About the Reviewers

Jason Dentler started tinkering with computers as a kid in the late 80s. As a college freshman, he got a job as an intern for a small call center company. Eight years later, he found himself coding for the entire call center division of a Fortune 500 company at their Global Technology Center in Las Vegas, Nevada. From there, he moved back to Texas and now works in higher education. He is an active participant in the NHibernate community and blogs about NHibernate, .NET, and programming in general at http://jasondentler.com.

I'd like to thank my NHibernate friends Fabio, Tuna, Jose, and Oren for their support and mentorship, and Scott Guthrie, who with a single tweet, literally made my blog an overnight success.

Fabio Maulo is the NHibernate development team leader.

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.

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.

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

Action 1Action 2Action 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."

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.

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

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 <[email protected]>, 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 <[email protected]>.

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.

Tip

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.

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 <[email protected]> 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 <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 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 itHBM mapping filesPlain Old CLR Objects (POCOs)Data access classesA simple web page databound to a collection of NHibernate objects

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 latestGA (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?

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.

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>

Plain Old CLR Object ( POCO )

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; } }

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, SelectCount, 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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="LoginGrid" AutoGenerateColumns="false" DataSourceID="LoginSource" runat="server"> <Columns> <asp:HyperLinkField HeaderText="ID" DataTextField="Id" SortExpression="Id" DataNavigateUrlFields="Id"DataNavigateUrlFormatString="~/SampleForms/Login.aspx?LoginId={0}"Target="_parent" /> <asp:BoundField HeaderText="FirstName" DataField="FirstName" /> <asp:BoundField HeaderText="LastName" DataField="LastName" /> <asp:BoundField HeaderText="UserName" DataField="UserName" /> <asp:BoundField HeaderText="Password" DataField="Password" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="LoginSource" TypeName="BasicWebApplication.DataAccess.LoginDataControl"DataObjectTypeName="BasicWebApplication.Common.DataObjects.Login" SelectMethod="GetAll" SelectCountMethod="GetCountOfAll" runat="server"></asp:ObjectDataSource> </form> </body> </html>

Summary

In this chapter, we talked a little bit about what NHibernate is, and why we should use it. We also touched on what HBM mapping files are and what they are used for, as well as the Plain Old CLR Objects (POCOs) that NHibernate actually maps data into. Neither of these would be very helpful to us without some Data Access Object (DAO) classes to tell NHibernate to retrieve or save the data we are working with. Finally we looked at a simple web page that was databound to a collection of NHibernate objects, all without any codebehind or other additional code.

It may seem like creating all these files is a lot of work, and it might be simpler to just go back to handcoding the SQL! I would tend to agree with you, if I didn't know the shortcut to creating all of these files—code generation, or even better, using Fluent NHibernate! If you can't wait, then sneak a peek at Chapter 4, Data Cartography, for more about Fluent NHibernate.

Now that we have skimmed the surface on how NHibernate works and how to make it work for us, let's talk about database layout and design, which is the subject of our next chapter.

Chapter 2. Database Layout and Design

Like the foundation of a building, the structure of your database forms the base for your entire application. If you take a little care and build it well, then your overall experience with any data access technology will be greatly improved.

In this chapter, we'll discuss:

Table layoutsNHibernate assigned IDsRelationshipsNormal form

One of the most important things you can do in your project is to lay out your data in a logical and efficient model. In this chapter, we'll discuss the fundamentals of a good database design and how to model your data effectively.

Before you get started