NHibernate Part II
CoderSource.net
NHibernate Part II - Article by azamsharp
Level: BeginnerType: Article
Rating: Page: 2 of 2

Date: 6/22/2005 12:00:00 AM

Environment: Windows, .Net, NHibernate

Add Method Code:

Now let's see the Add method that adds the user object into the database.

In future articles we will implement an interface and inherit from that interface to get the common functionality. But for now let's look at the easy way to add the object.

public static void Add(User user)

{// make the configuration file

Configuration cfg = new Configuration();

cfg.AddAssembly("Glasses");

ISessionFactory factory = cfg.BuildSessionFactory();

ISession session = factory.OpenSession();

ITransaction transaction = session.BeginTransaction();

session.Save(user);

transaction.Commit();

session.Close();

}

  • First we are making a Configuration object cfg
  • We load the assembly using the AddAssembly method
  • ISessionFactory interface creates a session factory which can be used to create sessions.
  • ISession interface is used to create independent session which is opened by using the factory.OpenSession() method
  • Once the session has been open than it means that you can communicate with the database.
  • ITransaction interface which begines the session transactions.
  • session.Save(user) is used to save the session.
  • transaction.Commit() is used to save the data to the database.
  • session.Close() finally closes the session.

The Client Code:

The Client code is pretty simple and self explanatory.

private void Button1_Click(object sender, System.EventArgs e)

{

User user = new User();

user.Email = "codersource@source.net";

user.Password = "mypassword";

user.Status = true;

user.DateCreated = DateTime.Now;

Test.User.Add(user);

}

Don't wait now and check your database. A new entry should be added if you have done everything right. Isn't this the coolest thing ever. In the upcoming articles we will see more features of NHibernate.

I hope you enjoyed the article. Happy programming !  


Attachments

Project Files NHibernateII

1 2

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us