NHibernate查询Sql查询

时间:2011-12-08 05:26:26

标签: c# sql nhibernate

让我解释一下我的情景。我有一个表HSPartList,它有partName,description,issueNo等。当进行搜索时,我有一个标准应该列出最新issueNo的所有部分。即。如果表数据如下:

|PartName| PartDesc| IssueNo|

TestPart1  TestPart1  1
TestPart1  TestPart1  2
TestPart2  TestPart2  1
TestPart2  TestPart2  2

在此示例中,当我搜索最新问题时,它应该只返回

|PartName| PartDesc| IssueNo|

TestPart1  TestPart1  2
TestPart2  TestPart2  2

我有sql查询。我需要将其转换为nHibernate查询。

SQL查询是:

select * from HS_PartList HS where HS.IsLive = 1 and HS.PartName Like '%test%' and IssueNo=(select max(issueNo) from HS_PartList where HS_PartList.PartName=HS.PartName)

NHibernate版本是2.1.2.4000

2 个答案:

答案 0 :(得分:2)

var subquery = DetachedCriteria.For<Part>()
    .Add(Restrictions.EqProperty("Name", "part.Name"))  <-- part is the alias of the main query
    .SetProjection(Projections.Max("IssueNo"));

var results = session.CreateCriteria<Part>("part")
    .Add(Restrictions.Eq("IsLive", true))
    .Add(Restrictions.Like("Name", teststring, MatchMode.Anywhere))
    .Add(Subqueries.Eq("IssueNo", subquery))
    .List();

答案 1 :(得分:2)

  Using Hql it Works fine 
string SearchTerm = "TestPart2";
string search = "and (partdetail.PartName like '%" + SearchTerm + "%') ";
var hql = string.Format(@"select partdetail  from HSPartList as partdetail  where  IssueNo =(select Max(IssueNo)  from HSPartList)") + search;
var context = _session.CreateQuery(hql).List<HSPartList>();