您的位置:首页 > 编程语言 > ASP

Asp.Net Nhibernate使用Criteria查询数据使用方法小记

sophia-yun 2012-09-10 15:33 155 查看
在Asp.Net中,使用Nhibernate将数据库表与实体映射,这样对数据库的操作就可以转化为对实体的操作,例如实体类RsUser与数据库表T_User映射后,查询数据库的操作就主要分为以下几种:

1. 获取满足某一条件的整个实体类信息NHibernate.Criterion.Expression.Eq用法

public IList<RsUser> GetUsersByCode()
{
  ICriteria criteria = Session.GetISession().CreateCriteria(typeof(RsUser));
criteria.Add(NHibernate.Criterion.Expression.Eq("Code", code));
return criteria.List<RsUser>();
}


2. 获取单个属性信息:NHibernate.Criterion.Projections.Property用法

public int GetUserIDByCode(string code)
{
  ICriteria criteria = Session.GetISession().CreateCriteria(typeof(RsUser))
  .Add(NHibernate.Criterion.Expression.Eq("Code", code))
   .SetProjection(NHibernate.Criterion.Projections.Property("ID"));
return criteria.UniqueResult<int>();
}


3. 给一条件集 只要满足其中一项:NHibernate.Criterion.Expression.In用法

public IList<RsUser> GetUsersByIDs(string ids)
{
  if (string.IsNullOrEmpty(ids))
  {
    ids = "";
}
IList<string> idStringList = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int[] idCollection = new int[idStringList.Count];
for (int i = 0; i < idStringList.Count; i++)
{
  idCollection[i] = int.Parse(idStringList[i]);
}
ICriteria criteria = GetNHibernateISession().CreateCriteria(typeof(RsUser))
  .Add(NHibernate.Criterion.Expression.In("ID", idCollection));
return criteria.List<RsUser>();
}


4. 模糊查询: NHibernate.Criterion.Expression.Like用法

public IList<RsUser> GetUsersBySearchContent(string content)
{
  string str = "%" + content + "%";
ICriteria criteria = Session.GetISession().CreateCriteria(typeof(RsUser));
criteria.Add(NHibernate.Criterion.Expression.Like("UserCode",str));
return criteria.List<RsUser>();
}


5. 取并集以及排序:NHibernate.Criterion.Expression.Or以及new NHibernate.Criterion.Order用法 false代表降序 true代表升序

public IList<RsUser> GetUsersBySearchContent(string content)
{
  string str = "%" + content + "%";
ICriteria criteria = Session.GetISession().CreateCriteria(typeof(RsUser));
criteria.Add(NHibernate.Criterion.Expression.Or(NHibernate.Criterion.Expression.Like("UserCode", str), NHibernate.Criterion.Expression.Like("UserTrueName", str)))
  .AddOrder(new NHibernate.Criterion.Order("RegisterTime", false));
  return criteria.List<RsUser>();
}
标签: 
相关文章推荐