Click here to Skip to main content
15,879,474 members
Articles / Web Development / ASP.NET

NHibernate Best Practices with ASP.NET, 1.2nd Ed.

Rate me:
Please Sign up or sign in to vote.
4.96/5 (322 votes)
11 Jun 2008CPOL60 min read 8.6M   35.9K   1.1K  
This article describes best practices for leveraging the benefits of NHibernate 1.2, ASP.NET, generics and unit testing together.
using System;
using NHibernateSample.Core.DataInterfaces;
using NHibernateSample.Data;
using NHibernateSample.Core.Domain;

public partial class EditCustomer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            DisplayCustomerToEdit();
        }
    }

    private void DisplayCustomerToEdit() {
        IDaoFactory daoFactory = new NHibernateDaoFactory();
        ICustomerDao customerDao = daoFactory.GetCustomerDao();

        // No need to lock the customer since we're just viewing the data
        Customer customerToEdit = customerDao.GetById(Request.QueryString["customerID"], false);

        hidCustomerID.Value = customerToEdit.ID;
        lblCustomerID.Text = customerToEdit.ID;
        txtCompanyName.Text = customerToEdit.CompanyName;
        txtContactName.Text = customerToEdit.ContactName;

        // The Orders collection is lazy-loaded
        grdOrders.DataSource = customerToEdit.Orders;
        grdOrders.DataBind();
    }

    protected void btnUpdate_OnClick(object sender, EventArgs e) {
        IDaoFactory daoFactory = new NHibernateDaoFactory();
        ICustomerDao customerDao = daoFactory.GetCustomerDao();

        // Now that we're about to update the customer, be sure to lock the entity
        Customer customerToUpdate = customerDao.GetById(hidCustomerID.Value, true);

        // Changes to the customer object will be automatically committed at the end of the HTTP request
        customerToUpdate.CompanyName = txtCompanyName.Text;
        customerToUpdate.ContactName = txtContactName.Text;

        Response.Redirect("ViewCustomers.aspx?action=updated");
    }

    protected void btnCancel_OnClick(object sender, EventArgs e) {
        Response.Redirect("ViewCustomers.aspx");
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions