Wednesday 16 March 2016

N-hibernate example for beginers using c# and MS sql

NHibernate:


NHibernate is an Object-Relational Mapping (ORM) solution for the .NET Platform. It provides a framework for mapping an object oriented domain model to a traditional relational database. It's primary feature is mapping from .NET classes to database tables and from CLR data types to SQL data types.

Why NHibernate?

In the past, we carefully hand-crafted our data access layers for the applications we wrote. We spent as much as 50% or more of our overall time to implement and maintain this data layer.It was not a very challenging task though, and a lot of repetitive coding was involved.
As we were not the only developers facing the problem of writing the data access code,some people started to write and publish a framework that would solve this problem. This was the birth of the ORM frameworks such as NHibernate. Nowadays, accessing relational data from an object-oriented application is a solved problem
Thus, writing your own data layer is a waste of time. Somebody even used a much more pronounced phrase to pinpoint this fact, "Writing your own data access layer is like stealing money from your client".

Example:

 In this example I am connecting test database with Emp table with primary key as ID and Name columns in "select * from Emp" query.

First Open-->new Project -->windows application(c#)-->named as(Nhibernatesample)

Step 1:Create class for table:(Emp.cs)

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace Nhibernatesample  
 {  
   public class Emp  
   {  
      public virtual int ID { get; set; }  
     public virtual string Name { get; set; }  
   }  
 }  

Here ID and Name are table Emp Columns.

Step 2:Create table Configuration(hbm.xml)

Add-->New Iem-->Data-->xml file-->named as Table name-->Emp.hbm.xml 

 <?xml version="1.0" encoding="utf-8" ?>  
 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"  
         assembly="Nhibernatesample"  
         namespace="Nhibernatesample">  
  <class name="Nhibernatesample.Emp" table="Emp">  
   <id name="ID" column="ID" type="Int32" unsaved-value="0">  
    <generator class="native">  
    </generator>  
   </id>  
   <property name="Name" />  
  </class>  
 </hibernate-mapping>  


Here  Project name as assembly="Nhibernatesample" namespace="Nhibernatesample" and class name "Nhibernatesample.Emp" and table name "Emp".Then Id is int32 and Name is name column.

Finally Emp.hbm.xml  --> Right-click-->properties-->Build Action-->(change)Embedded Resource

 Step 3: Write the Code in Sample Form1 in Button Click:

First add namesapce using addind two dll files in bin-->debug folder.Files are

i)Iesi.Collections.dll
ii)NHibernate.dll

Then Project-->add reference-->Browse-->bin-->debug add two dlls one by one.

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Text;  
 using System.Windows.Forms;  
 using System;  
 using NHibernate.Cfg;  
 using NHibernate.Dialect;  
 using NHibernate.Driver;  
 using System.Reflection;  
 namespace Nhibernatesample  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       var cfg = new Configuration();  
       cfg.DataBaseIntegration(x =>  
       {  
         x.ConnectionString = @"Server=245.245.245.245\sql2005;DataBase=test;UID=sa;Pwd=testpass";  
         x.Driver<SqlClientDriver>();  
         x.Dialect<MsSql2005Dialect>();  
       });  
       cfg.AddAssembly(Assembly.GetExecutingAssembly());  
       var sessionFactory = cfg.BuildSessionFactory();  
       using (var session = sessionFactory.OpenSession())  
       {  
         using (var tx = session.BeginTransaction())  
         {  
           var datas = session.CreateCriteria<Emp>()  
             .List<Emp>();  
           if (datas.Count > 0)  
             {  
               dataGridView1.Visible = true;  
               dataGridView1.Refresh();  
               dataGridView1.DataSource = datas;  
             }  
           tx.Commit();  
         }  
       }  
     }  
   }  
 }  

In my Project I am using sql 2005. If you using Ms sql 2010 or 2012  use MsSql2010Dialect or MsSql2012Dialect in x.Dialect.

Finally We got the Result in Button1_click Event.

 


No comments:

Post a Comment