A simple example of nhib.pdf is provided.
Nhib.pdf use small example 1. Create a Model class library project.
Use the code generator to generate a Model class.
Here we use a simple UserInfo table as an example.
Note that the field must startVirtual.
namespace Model{ public partial class UserInfo { public virtual System.Int32 Id { get; set; } public virtual System.String Name { get; set; } }}2. Compile the ing file between ing object classes and databases.
Create an xml file namedUserInfo. hbm. xmlYou must useTable name. hbm. xmlAnd change its generation operation to"Embedded Resources", Because NHibernate will look for ing relationships in this way.
<?xml version="1.0" encoding="utf-8" ?>3. Create a DAL class library project.
Create a new NHibernateHelper class as the factory for production and Session management.
namespace DAL{ public class NHibernateHelper { private ISessionFactory _sessionFactory; public NHibernateHelper() { _sessionFactory = GetSessionFactory(); } private static ISessionFactory GetSessionFactory() { return (new Configuration()).Configure().BuildSessionFactory(); } public ISession GetSession() { return _sessionFactory.OpenSession(); } }}
Ensure that each object of the NHibernate class has only one Session.
4. Create a UserInfoDAL class to add, delete, modify, and query UserInfo data.
namespace DAL{ public partial class UserInfoDAL { private ISession _isession; public UserInfoDAL() { _isession = new NHibernateHelper().GetSession(); } public void Add(UserInfo u) { _isession.Save(u); _isession.Flush(); } public bool Update(UserInfo u) { try { _isession.Update(u); _isession.Flush(); return true; } catch (Exception ex) { return false; } finally { _isession.Close(); } } public bool Delete(UserInfo u) { try { _isession.Delete(u); _isession.Flush(); return true; } catch (Exception ex) { return false; } finally { _isession.Close(); } } public UserInfo GetById(int id) { return _isession.Get<UserInfo>(id); } public IList<UserInfo> GetList() { IList<UserInfo> list = _isession.QueryOver<UserInfo>().List(); return list; } }}
5. Create a console test project call
Because BLL and UI layers are not the focus of this article, dependency injection, layering, and interfaces are not considered. This article mainly introduces the configuration of nhib.pdf.
Add an xml file in the console project namedHibernate. cfg. xmlIt cannot be changed and changed to "copy if it is newer ".