Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

NHibernate 4.x Cookbook - Second Edition
NHibernate 4.x Cookbook - Second Edition
NHibernate 4.x Cookbook - Second Edition
Ebook1,112 pages4 hours

NHibernate 4.x Cookbook - Second Edition

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Master the full range of NHibernate features through detailed example recipes that you can quickly apply to your own applications
  • Reduce hours of application development time and get a better application architecture and improved performance
  • Create, maintain, and update your database structure automatically with the help of NHibernate
Who This Book Is For

This book is written for .NET developers who want to use NHibernate and those who want to deepen their knowledge of the platform. Examples are written in C# and XML. Some basic knowledge of SQL is assumed. If you build .NET applications that use relational databases, this book is for you.

LanguageEnglish
Release dateJan 31, 2017
ISBN9781784394110
NHibernate 4.x Cookbook - Second Edition

Related to NHibernate 4.x Cookbook - Second Edition

Related ebooks

Software Development & Engineering For You

View More

Related articles

Reviews for NHibernate 4.x Cookbook - Second Edition

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    NHibernate 4.x Cookbook - Second Edition - Jason Dentler

    Table of Contents

    NHibernate 4.x Cookbook Second Edition

    Credits

    About the Authors

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why Subscribe?

    Customer Feedback

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Sections

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Downloading the color images of this book

    Errata

    Piracy

    Questions

    1. The Configuration and Schema

    Introduction

    Installing NHibernate

    Getting ready

    How to do it...

    There's more…

    Configuring NHibernate with hibernate.cfg.xml

    Getting ready

    How to do it...

    How it works...

    There's more...

    NHibernate architecture

    NHibernate properties

    Dialects and drivers

    See also

    Configuring NHibernate with App.config or Web.config

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Configuring NHibernate with code

    Getting ready

    How to do it…

    How it works…

    There's more...

    See also

    Configuring NHibernate with Fluent NHibernate

    Getting ready

    How to do it…

    How it works…

    See also

    Configuring NHibernate logging

    Getting ready

    How to do it...

    How it works...

    There's more...

    Using logger to troubleshoot NHibernate

    Using other log providers

    See also

    Generating the database

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Scripting the database

    Getting ready

    How to do it...

    How it works...

    See also

    Updating the database

    Getting ready

    How to do it...

    How it works...

    See also

    Using NHibernate schema tool

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    2. Models and Mappings

    Mapping a class with XML

    Getting ready

    How to do it…

    How it works…

    There's more…

    What happens to these mappings?

    Surrogate keys and natural IDs

    ID generator selection

    See also

    Creating class hierarchy mappings

    Getting ready

    How to do it…

    How it works…

    There's more…

    Table per class

    Table per concrete class

    See also

    Creating class components

    Getting ready

    How to do it…

    How it works…

    Mapping a one-to-many relationship

    Getting ready

    How to do it…

    How it works…

    There's more…

    Lazy loading collections

    Lazy loading proxies

    Collections

    Bags

    Lists

    Sets

    Map

    See also

    Mapping a many-to-many relationship

    Getting ready

    How to do it…

    How it works…

    There's more…

    Mapping collections of elements and components

    Getting ready

    How to do it…

    How it works…

    There's more…

    Setting up a base entity class

    How to do it…

    How it works…

    There's more…

    See also

    Handling versioning and concurrency

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Mapping by code

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Mapping by convention

    Getting ready

    How to do it…

    How it works…

    There's more…

    Creating mappings fluently

    Getting ready

    How to do it…

    How it works…

    See also

    Bidirectional one-to-many class relationships

    How to do it…

    How it works…

    There's more…

    Mapping enumerations

    How to do it…

    How it works…

    Unnecessary updates

    See also

    Immutable entities

    Getting ready

    How to do it…

    How it works…

    Mapping relations to non-primary keys

    Getting ready

    How to do it…

    How it works…

    There's more…

    Using lazy properties

    Getting ready

    How to do it…

    How it works…

    Mapping joins

    Getting ready

    How to do it…

    How it works…

    There's more…

    Using calculated properties

    Getting ready

    How to do it…

    How it works…

    There's more…

    Using serializable values

    Getting ready

    How to do it…

    How it works…

    There's more…

    Dynamic components

    Getting ready

    How to do it…

    How it works…

    There's more…

    Mapping

    Getting ready

    How to do it…

    How it works…

    3. Sessions and Transactions

    Introduction

    Setting up session-per-web request

    Getting ready

    Option 1: Using the companion library

    Option 2: Manual setup

    How to do it…

    How it works…

    There's more…

    See also

    Setting up session-per-presenter

    How to do it…

    How it works…

    There's More…

    See also

    Creating a session ASP.NET MVC action filter

    Getting ready

    How to do it…

    How it works…

    What about Web API?

    There's more…

    View models

    See also

    Creating a transaction ASP.NET MVC action filter

    Getting ready

    How to do it…

    How it works…

    There's more…

    Save entities to the database

    Getting ready

    How to do it…

    How it works…

    Save

    Update

    SaveOrUpdate

    Persist

    Using different flush modes

    Commit

    Auto

    Always

    Never

    Using session.Merge

    Getting ready

    How to do it…

    How it works…

    See also

    Using session.Refresh

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Handle concurrency using session.Lock

    Getting ready

    How to do it…

    How it works…

    None

    Read

    Upgrade

    UpgradeNoWait

    There's more…

    Using dictionaries as entities

    Getting ready

    How to do it...

    How it works…

    There's more…

    Partially dynamic

    Using NHibernate with transaction scope

    Getting ready

    How to do it…

    How it works…

    See also

    4. Queries

    Introduction

    Getting ready

    Query entities by ID

    Getting ready

    How to do it…

    How it works…

    Session.Get

    Session.Load

    The session cache jumps in

    Using LINQ to NHibernate

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using CriteriaQueries

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using QueryOver

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using QueryOver projections and aggregates

    Getting ready

    How to do it…

    How it works…

    See also

    Using the Hibernate Query Language

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using native SQL

    Getting ready

    How to do it…

    How it works…

    Eager loading with LINQ

    Getting ready

    How to do it…

    How it works…

    There's more…

    Limiting the result set doesn't work

    Eager loading multiple collections should be avoided

    Use batching as an alternative solution

    See also

    Eager loading with Criteria

    Getting ready

    How to do it…

    How it works…

    Eager loading with QueryOver

    Getting ready

    How to do it…

    How it works…

    Eager loading with HQL

    Getting ready

    How to do it…

    How it works…

    Eager loading with SQL

    Getting ready

    How to do it…

    How it works…

    Using named queries

    Getting ready

    How to do it…

    How it works…

    Named SQL queries

    There's more…

    See also

    Using detached queries

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using HQL for bulk data changes

    Getting ready

    How to do it…

    How it works…

    There's more…

    Bulk inserts

    See also

    Filtering collections

    Getting ready

    How to do it…

    How it works…

    There's more…

    Using result transformers

    How to do it…

    How it works…

    There's more…

    DistinctRootEntity

    AliasToEntityMap

    PassThrough

    RootEntity

    ToList

    AliasToBean

    AliasToBeanConstructor

    Creating your own transformer

    Extra lazy collections

    Getting ready

    How to do it…

    How it works…

    There's more…

    5. Improving Performance

    Reducing application startup time

    Getting ready

    How to do it…

    How it works…

    There's more…

    Using MultiCriteria

    Getting ready

    How to do it…

    How it works…

    See also

    Using MultiQuery

    Getting ready

    How to do it…

    How it works…

    See also

    Using Futures

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Eager loading child collections

    Getting ready

    How to do it...

    How it works...

    Problem 1 – limiting the result set doesn't work

    Problem 2 – only the queried class' properties can be eager loaded

    Problem 3 – eager loading multiple collections should be avoided

    There's more…

    Criteria

    QueryOver

    See also

    Using stateless sessions

    Getting ready

    How to do it...

    How it works...

    There's more...

    Using read-only entities

    Getting ready

    How to do it...

    How it works...

    Setting the session to be read-only

    Setting a query to load entities as read-only

    Making a specific entity read-only

    There's more...

    Use the second-level cache

    Getting ready

    How to do it...

    How it works...

    There's more...

    Entity cache

    Query cache

    Update timestamp cache

    The rules

    See also

    Configuring the second-level cache with code

    Getting ready

    How to do it...

    How it works...

    There's more…

    See also

    Sharding databases for performance

    Getting ready

    How to do it...

    How it works...

    6. Testing

    Introduction

    Using NHibernate Profiler

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Profiling NHibernate with Glimpse

    Getting ready

    How to do it...

    How does it work...

    See also

    Fast testing with the SQLite in-memory database

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Preloading data with SQLite

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Using Fluent NHibernate persistence testing

    Getting ready

    How to do it...

    How it works...

    See also

    Using the Ghostbusters test

    Getting ready

    How to do it...

    How it works...

    See also

    7. Data Access Layer

    Introduction

    Transaction auto-wrapping for the data access layer

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Setting up an NHibernate repository

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using named queries in the data access layer

    Getting ready

    How to do it…

    How it works…

    See also

    Using ICriteria in the data access layer

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using paged queries in the data access layer

    Getting ready

    How to do it…

    How it works…

    See also

    Using LINQ specifications in the data access layer

    Getting ready

    How to do it…

    How it works…

    There's more…

    Specification composition

    See also

    8. Extending NHibernate

    Introduction

    Creating an encrypted string type

    How to do it…

    How it works…

    There's more…

    See also

    Creating a money type

    How to do it…

    How it works…

    There's more…

    See also

    Using well-known instance types

    How to do it…

    How it works…

    See also

    Using dependency injection with entities

    Getting ready

    How to do it…

    How it works…

    There's more…

    Bland passwords need salt

    See also

    Creating an audit-event listener

    How to do it…

    How it works…

    There's more…

    See also

    Creation and change stamping of entities

    How to do it…

    How it works…

    See also

    Generating trigger-based auditing

    Getting ready

    How to do it…

    How it works…

    See also

    Implementing a soft-delete pattern

    How to do it…

    How it works…

    There's more…

    See also

    Setting Microsoft SQL's Context_Info

    Getting ready

    How to do it…

    How it works…

    See also

    Using dynamic connection strings

    How to do it…

    How it works…

    See also

    Using custom dialect functions

    How to do it…

    How it works…

    See also

    Using custom functions in LINQ

    Getting ready

    How to do it…

    How it works…

    See also

    Extending the LINQ provider

    Getting ready

    How to do it…

    How it works…

    See also

    9. NHibernate Contribution Projects

    Introduction

    Property validation with attributes

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating validator classes

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Setting up full-text searches

    Getting ready

    How to do it…

    How it works…

    There's more…

    Auditing data with Envers

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using NHibernate Spatial

    Getting ready

    How to do it…

    How it works…

    There's more…

    Geography or geometry?

    What's this SRID?

    Spatial data types

    Index

    NHibernate 4.x Cookbook Second Edition


    NHibernate 4.x Cookbook Second Edition

    Copyright © 2017 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 authors, 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: October 2010

    Second edition: January 2017

    Production reference: 1200117

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78439-642-8

    www.packtpub.com

    Credits

    Authors

    Gunnar Liljas

    Alexander Zaytsev

    Jason Dentler

    Reviewer

    Amro El-Fakharany

    Commissioning Editor

    Dipika Gaonkar

    Acquisition Editor

    Prachi Bisht

    Content Development Editor

    Trusha Shriyan

    Technical Editor

    Varsha Shivhare

    Copy Editor

    Sneha Singh

    Project Coordinator

    Kinjal Bari

    Proofreader

    Safis Editing

    Indexer

    Rekha Nair

    Graphics

    Kirk D'Penha

    Production Coordinator

    Arvindkumar Gupta

    Cover Work

    Arvindkumar Gupta

    About the Authors

    Gunnar Liljas is a software architect with more than 20 years' experience in developing and designing web-based solutions. His focus has been on data-driven content publishing, not only for the Web, but also for automated and on-demand print publishing. Currently, he spends most of his waking hours at the Swedish CRM supplier Revide, where he uses tools such as NHibernate and Redis to create targeted emails, text messages, and campaign web sites based on massive data sources.

    He's also one of the lead contributors to the NHibernate open source project.

    In his spare time, Gunnar sings in two classical choirs and often performs with the renowned Norrköping Symphony Orchestra.

    Alexander Zaytsev discovered his passion for IT when he was a small kid, and since then he has dedicated his life to becoming an excellent software developer. Alexander has many years' experience in the IT field, analyzing, designing, and developing .NET-based enterprise applications, using cutting-edge technologies. He works as an independent consultant in the .NET space, providing technical expertise to all kinds of software development companies. He is an active member of open source and local development communities, and writes a blog at http://alexzaytsev.me. He is one of the main contributors to the NHibernate project, and one of the few people who really know the NHibernate internals.

    He is adept in Agile software development, and he believes that Agile practices such as test-driven development, pair programming, automated testing, continuous integration, and deployment are the keys to quality software.

    He lives in Auckland with his wife, Olga, and son, Stepan. In his spare time, he loves spending time with his family, cycling, and doing coding just for fun.

    Jason Dentler grew up in the small Texas town of Mission Valley. He started tinkering with computers as a kid in the late 1980s, and all these years later, he hasn't stopped. He's worked in a few different industries. Currently, he builds really awesome software in higher education. He's an Eagle Scout and a graduate of the University of Houston – Victoria.

    I'd like to thank my family and friends for all their support, and especially my parents, who encouraged and tolerated my computer obsession all those years. Thanks, Mom & Dad. I love you.

    About the Reviewer

    Amro El-Fakharany has more than 15 years' experience as a software developer. Coming from an electrical engineering background, he has a passion for solving industrial problems, and maintaining and extending those solutions. In 2002, he established an engineering consultancy helping and providing solutions in the bulk-material-handling sector. He has been working with NHibernate since its early days and is also a contributor to the project.

    www.PacktPub.com

    eBooks, discount offers, and more

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

    You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: <customerreviews@packtpub.com>.

    Preface

    This book explains many features of NHibernate 4 in detail through example recipes that you can quickly apply to your applications. These recipes will take you from the absolute basics of NHibernate through its most advanced features and beyond, showing you how to take full advantage of each concept to quickly create amazing database applications.

    What this book covers

    Chapter 1, The Configuration and Schema, explains various methods for configuring NHibernate and generating your database.

    Chapter 2, Models and Mappings, introduces mappings in both XML and code, and includes more advanced topics such as versioning and concurrency.

    Chapter 3, Sessions and Transactions, covers several techniques for proper session and transaction management in your application, including distributed transactions.

    Chapter 4, Queries, demonstrates a number of rich query APIs, including the LINQ provider and the QueryOver API.

    Chapter 5, Improving Performance, lets you know how to reduce application startup time by using serialized configuration. We also dig deep into how caching and advanced querying techniques can improve the performance of your application.

    Chapter 6, Testing, introduces some techniques you can apply to quickly test your NHibernate applications and includes an introduction to NHibernate Profiler.

    Chapter 7, Data Access Layer, shows how to build a flexible, extensible data access layer based on NHibernate and its many query APIs.

    Chapter 8, Extending NHibernate, shows a number of ways to customize and extend NHibernate to provide additional services such as audit logging and data encryption.

    Chapter 9, NHibernate Contribution Projects, introduces several NHibernate Contribution projects, adding features such as caching, data validation, full text search, geospatial data, and horizontal partitioning of databases.

    What you need for this book

    To complete the recipes in this book, you'll need the following tools:

    Windows 7 or later versions

    Visual Studio 2015 or later versions

    Microsoft SQL Server 2008 Express edition or later versions

    Who this book is for

    This book is written for .NET developers who want to use NHibernate and those who want to deepen their knowledge of the platform. Examples are written in C# and XML. Some basic knowledge of SQL is assumed. If you build .NET applications that use relational databases, this book is for you.

    Sections

    In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it work, There's more, and See also).

    To give clear instructions on how to complete a recipe, we use these sections as follows:

    Getting ready

    This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

    How to do it…

    This section contains the steps required to follow the recipe.

    How it works…

    This section usually consists of a detailed explanation of what happened in the previous section.

    There's more…

    This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

    See also

    This section provides helpful links to other useful information for the recipe.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Add a new folder named NamedQueries to the project.

    A block of code is set as follows:

    var sessionFactory = ProductModel

      .CreateExampleSessionFactory(true);

    var kernel = new StandardKernel();

    kernel.Load(new NinjectBindings());

    kernel.Bind()

    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 BooksController : Controller

    {

      [NHibernateSession]

     

      public ActionResult Index()

      {

        var books = DataAccessLayer.GetBooks()

    Any command-line input or output is written as follows:

    Install-Package NHibernate -project SessionRecipes

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Don't forget to set the Build action to Embedded Resource.

    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 disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at 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

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    Downloading the color images of this book

    We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/NHibernate4_0Cookbook_ColorImages.pdf.

    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 could 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/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted 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

    If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.

    Chapter 1. The Configuration and Schema

    In this chapter, we will cover the following recipes:

    Installing NHibernate

    Configuring NHibernate with hibernate.cfg.xml

    Configuring NHibernate with App.config or Web.config

    Configuring NHibernate with code

    Configuring NHibernate with Fluent NHibernate

    Configuring NHibernate logging

    Generating the database

    Scripting the database

    Updating the database

    Using NHibernate schema tool

    Introduction

    NHibernate is a popular, mature, open source Object-Relational Mapper (ORM) based on Java's Hibernate project. ORMs, such as LINQ to SQL, Entity Framework, and NHibernate, translate between the database's relational model of tables, columns, and keys to the application's object model of classes and properties.

    The NHibernate homepage, http://nhibernate.info, contains blog posts, the complete reference documentation, and a bug tracker. Support is available through the very active nhusers Google group at http://groups.google.com/group/nhusers. The NHibernate source code is hosted on GitHub at http://github.com/nhibernate/nhibernate-core. Precompiled binaries of NHibernate releases are also available on SourceForge and through NuGet at http://nuget.org/packages/NHibernate.

    NHibernate provides an incredible number of configuration options and settings. The recipes in this chapter demonstrate several methods for configuring NHibernate and generating the necessary database schema.

    Installing NHibernate

    Before we begin, let's get our Visual Studio solution and database set up. The following information will get you up and started with NHibernate.

    Getting ready

    Install Microsoft SQL Server 2012 Express (or a newer version) on your PC, using the default settings.

    Create a blank database named NHCookbook.

    How to do it...

    In Visual Studio, create a new C# class library project named Eg.Core with a directory for the solution named Cookbook.

    Delete the Class1.cs file.

    In the Solution Explorer, right click the References node in the Eg.Core project and select Manage NuGet Packages. In the top navigation of the now-opened NuGet Package Manager, make sure Browse is selected. Enter the word NHibernate in the search box and wait for the results to show up:

    Select the NHibernate package in the search results and click Install. This will install NHibernate and all required dependencies.

    Add a new class named TestClass, to the Eg.Core project:

    public class TestClass

    {

      public virtual int Id { get; set; }

      public virtual string Name { get; set; }

    }

    There's more…

    Instead of using the graphical package manager, you can use the Package Manager Console. It provides a faster way to install or update NuGet packages. To open the Package Manager Console simply click Tools | NuGet Package Manager | Package Manager Console. In the opened window you can simply write the following:

    Install-Package NHibernate -Project Eg.Core

    This will produce the same effect as the main recipe.

    Configuring NHibernate with hibernate.cfg.xml

    NHibernate offers several methods for configuration and a number of configuration settings.

    In this recipe, we will show you how to configure NHibernate using the hibernate.cfg.xml configuration file, with a minimal number of settings to get your application up and running quickly. The recipe also forms the base for several other recipes in this chapter.

    Getting ready

    Complete the steps from the Installing NHibernate recipe in this chapter.

    Add a console application project to your solution called ConfigByXml.

    Set it as the Startup project for your solution.

    Install NHibernate to ConfigByXml project using the NuGet Package Manager Console.

    In ConfigByXml, add a reference to the Eg.Core project.

    How to do it...

    Add an XML file named hibernate.cfg.xml with the following contents:

    1.0 encoding=utf-8?>

    urn:nhibernate-configuration-2.2>

     

        dialect>

          NHibernate.Dialect.MsSql2012Dialect, NHibernate

       

        connection.connection_string>

          Server=.\SQLEXPRESS; Database=NHCookbook;

          Trusted_Connection=SSPI

       

        adonet.batch_size>

          100

       

     

    On the Solution Explorer tab, right-click on hibernate.cfg.xml and select Properties.

    Change Copy to Output Directory property from Do not copy to Copy if newer.

    Open Program.cs and add using NHibernate.Cfg; to the beginning of the file

    Add the following code to the Main method:

    var nhConfig = new Configuration().Configure();

    var sessionFactory = nhConfig.BuildSessionFactory();

    Console.WriteLine(NHibernate Configured!);

    Console.ReadKey();

    Build and run your application. You will see the text NHibernateConfigured!

    How it works...

    The connection string we've defined points to the NHCookbook database running under the local Microsoft SQL Server.

    Next, we define a few properties that tell NHibernate how to behave.

    The dialect property specifies a dialect class that NHibernate uses to build

    Enjoying the preview?
    Page 1 of 1