Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Update & Delete Operation

NHibernate is a open source Object-Relational Mapping (ORM) tool. This ORM tool hides sql query complexities by replacing query with mapping and class object.

I already have article about basic NHibernate in previous post. If you are new to Nhibernate then I recommend to Click here Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Select & Insert Operation first.

Lets recap what we have to do to work with NHibernate.

  1. Download necessary NHibernate file including NHibernate.dll & configuration template/example at http://sourceforge.net/projects/nhibernate
  2. Create xml mapping file and a class which representates DB table
  3. Include Nhibernate dll file, NHibernate xml configuration file, class library (if you have separate class project), and Asp.Net file it self
  4. Write codes inside the Asp.Net file that contains NHibernate configuration class object initialization, AddAssembly to Class Library, BuildSessionFactory, OpenSession, BeginTransaction, SaveOrUpdate, Commit to save data to DB.
  5. Write SQL Query replacement with QueryOver<T>() method and Where filter (if necessary) that has LinQ like syntax to retrieve record(s) and automatically convert to a class


This blog post contains example of Update & Delete Operation. To know more basic ‘Select’ & ‘Insert’ then go to previous post at this Url Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Select & Insert Operation.

I continue this example from that previous source code so I dont write them from start. I already have a Person Table, Class Library Project -> PersonLibrary contains Person class and XML mapping file.
Also I have Asp.Net that retrieve all records in Person Table. I already include a reference to PersonLibrary.dll & NHibernate.dll and also have NHibernate configuration Xml file.
Now I just want to add two links which are ‘Edit’ & ‘Delete’ in aspx page and those links functionality will be accomplished with NHibernate.

Add links to Literal Control’s Text in view record page (Default.aspx.cs)

At previous example, I display records data in Literal Control for demonstration purpose. Here I add html ‘Edit’ & ‘Delete’ links to literal’s text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using NHibernate.Cfg;
using PersonLibrary;
using System.Text;

namespace PersonWebNHB
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PopulatePerson();
        }

        protected void PopulatePerson()
        {
            Configuration config = new Configuration();
            config.Configure();

            config.AddAssembly("PersonLibrary");
            ISessionFactory factory = config.BuildSessionFactory();
            ISession session = factory.OpenSession();
            IList<Person> persList = session.QueryOver<Person>().List<Person>();
            session.Close();

            StringBuilder sb = new StringBuilder();
            foreach (Person pers in persList)
            {
                sb.Append(pers.PersonID + " " + pers.Name + " " + pers.City + " " + pers.Province + " ");
                sb.Append("<a href='editform.aspx?id=" + pers.PersonID + "'>Edit</a> &nbsp;<a href='delete.ashx?id=" + pers.PersonID + "'>Delete</a><br>");
            }
            Literal1.Text = sb.ToString();

            
        }
    }
}

Create Edit Form (editform.aspx)

I retrieve single record and show its value in textboxes & hiddenfield for reference ID.

<form id="form1" runat="server">
    <div>
    Person ID: <asp:Label ID="lbl" runat="server" Text="#"></asp:Label> <asp:HiddenField id="hdid" runat="server" /><br />
    Name: <asp:TextBox ID="txname" runat="server"></asp:TextBox><br />
    City: <asp:TextBox ID="txcity" runat="server"></asp:TextBox><br />
    Province: <asp:TextBox ID="txprovince" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnsave" runat='server' Text="Update" />
    </div>
   </form>

So if btnsave button is clicked then the data is updated and edit page will redirect to view page, default.aspx.

The editform.aspx.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using NHibernate.Cfg;
using PersonLibrary;

namespace PersonWebNHB
{
    public partial class editform : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Int32 id;
            if (!Page.IsPostBack)
            {
                id = Convert.ToInt32(Request.QueryString["id"]);
                hdid.Value = id.ToString();

                lbl.Text = id.ToString();
                ISession session = NHibernateCfg_Session();
                Person pers = session.QueryOver<Person>().Where(x => x.PersonID == id).SingleOrDefault<Person>();
                txname.Text = pers.Name;
                txcity.Text = pers.City;
                txprovince.Text = pers.Province;
                session.Close();
            }
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            Int32 id;
            id = Convert.ToInt32(hdid.Value);

            ISession session = NHibernateCfg_Session();
            Person pers = session.QueryOver<Person>().Where(x => x.PersonID == id).SingleOrDefault<Person>();

            ITransaction transaction = session.BeginTransaction();
            pers.Name = txname.Text;
            pers.City = txcity.Text;
            pers.Province = txprovince.Text;
            transaction.Commit();
            session.Close();

            Response.Redirect("Default.aspx");
        }

        protected ISession NHibernateCfg_Session()
        {
            Configuration cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly("PersonLibrary");
            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();

            return session;
        }
    }
}

If it is not postback mode then person’s id retrieved via Querystring otherwise it is retrieved from hiddenfield’s value.
I have NHibernateCfg_Session method that returns ISession due to repetitive code used in both display and update.
QueryOver method has ‘Where’ filter to PersonID and use LinQ syntax.

To save an update just set new Person class property value and do transaction.Commit() for saving the data actually.

Create Delete functionallity

I use generic handler, ashx file to delete specific record. The reason with using ashx file is that I dont need any user form/control in delete operation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using PersonLibrary;

namespace PersonWebNHB
{
    /// <summary>
    /// Summary description for delete
    /// </summary>
    public class delete : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Configuration cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly("PersonLibrary");

            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();

            Int32 id = Convert.ToInt32(context.Request.QueryString["id"]);

            ITransaction transaction = session.BeginTransaction();
            Person pers = session.QueryOver<Person>().Where(x => x.PersonID == id).SingleOrDefault<Person>();
            session.Delete(pers);
            transaction.Commit();
            session.Close();
            context.Response.Redirect("Default.aspx");

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Retrieve a single record and Session.Delete(pers); along with transaction.Commit(); will do the delete thing.

Regards,
Agung Gugiaji

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s