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