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

Simple NHibernate Architecture

Rate me:
Please Sign up or sign in to vote.
4.91/5 (38 votes)
11 Sep 2012CPOL3 min read 133.8K   3.2K   145  
An article showing a nice architecture I've come up for using NHibernate
using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Business;

public partial class _Default : System.Web.UI.Page 
{
	private Product _product
	{
		get { return (Product) Session["Product"];}
		set { Session["Product"] = value; }
	}
    protected void Page_Load(object sender, EventArgs e)
    {
		if (!this.IsPostBack)
		{			
			Bind();
		}
    }

	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);
		this.gvProduct.RowEditing +=new GridViewEditEventHandler(gvProduct_RowEditing);
		this.gvProduct.RowDeleting += new GridViewDeleteEventHandler(gvProduct_RowDeleting);
		this.btnSave.Click += new EventHandler(btnSave_Click);
	}

	void btnSave_Click(object sender, EventArgs e)
	{
		if (_product == null)
			_product = new Product();
		_product.Name = txtName.Text;
		_product.Weight = Convert.ToDecimal(txtWeight.Text);
		_product.Save();
		ClearFields();
		Bind();
	}

	void gvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
		Product product = Product.Get(Convert.ToInt32(gvProduct.DataKeys[e.RowIndex].Value));
		product.Delete();
		Bind();
	}

	void gvProduct_RowEditing(object sender, GridViewEditEventArgs e)
	{
		_product = Product.Get(Convert.ToInt32( gvProduct.DataKeys[e.NewEditIndex].Value ));
		txtName.Text = _product.Name;
		txtWeight.Text = _product.Weight.ToString();
	}

	private void Bind()
	{
		gvProduct.DataSource = Product.Select();
		gvProduct.DataKeyNames = new string[] { "ID" };
		gvProduct.DataBind();
	}

	private void ClearFields()
	{
		txtName.Text = "";
		txtWeight.Text = "";
		_product = null;
	}
}

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
Software Developer (Senior) Intelligent Coder
Canada Canada
I've been developing .NET enterprise applications since 2000.

I am originally from Rio de Janeiro and I am currently working at http://www.intelligentcoder.com in Ontario.

I also have my own startup where we offer client intake forms.

Comments and Discussions