NHibernate1.2 实现增、删、改、查 功能!!!
说明:login 为数据库表的实体类
public class UserAccess
{
//构造函数
public UserAccess()
{
cfg.AddAssembly("Entitys");
}
private NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
private ISession session = null; //会话工厂
private ITransaction tran = null; //事务处理
private string m_error = "";
/// <summary>
/// 获取错误信息
/// </summary>
public string Error
{
get { return this.m_error; }
}
/// <summary>
/// 添加
/// </summary>
/// <returns></returns>
public bool InsertUser(login l)
{
try
{
session = cfg.BuildSessionFactory().OpenSession();
tran = session.BeginTransaction();
session.Save(l);
tran.Commit();
}
catch (Exception ex)
{
tran.Rollback();
this.m_error = ex.Message;
return false;
}
finally
{
this.session.Close();
}
return true;
}
/// <summary>
/// 修改
/// </summary>
/// <returns></returns>
public bool UpdateUser(login l,int id)
{
try
{
session = cfg.BuildSessionFactory().OpenSession();
tran = session.BeginTransaction();
session.Update(l,id);
tran.Commit();
}
catch(Exception ex)
{
tran.Rollback();
this.m_error = ex.Message;
return false;
}
finally
{
this.session.Close();
}
return true;
}
/// <summary>
/// 删除
/// </summary>
/// <returns></returns>
public bool IDelUser(int ID)
{
try
{
session = cfg.BuildSessionFactory().OpenSession();
tran = session.BeginTransaction();
login l = (login)session.Load(typeof(login), ID);
session.Delete(l);
tran.Commit();
}
catch(Exception ex)
{
tran.Rollback();
this.m_error = ex.Message;
return false;
}
finally
{
this.session.Close();
}
return true;
}
/// <summary>
/// 查找一条数据
/// </summary>
/// <returns></returns>
public Entitys.login SelectUserByID(int ID)
{
try
{
session = cfg.BuildSessionFactory().OpenSession();
login l = (login)session.Load(typeof(login), ID);
return l;
}
catch (Exception ex)
{
this.m_error = ex.Message;
return null;
}
finally
{
this.session.Close();
}
}
///// <summary>
///// 查看
///// </summary>
///// <returns></returns>
//public int GetUsers()
//{
// try
// {
// }
// catch(Exception ex)
// {
// return -1;
// throw(ex);
// }
//}
}