1

标准:

var subQuery = DetachedCriteria.For<RecordInfo>();
    .Add(Restrictions.Eq("Property1", "some string"))
    .Add(Restrictions.EqProperty("Property2", "record.Id"))
    .SetProjection(Projections.Max("Id"));

var criteria = session.CreateCriteria(typeof(Record), "record")
    .CreateAlias("record.ListOfRecordInfo", "recordInfo")
    .Add(Subqueries.PropertyEq("recordInfo.Id", subQuery));

将为 Sybase ASE 15.5 方言生成类似这样的内容:

SELECT this_.Record_Id as Record1_2_3
...
FROM Record this_
INNER JOIN Record_Info Record_Info_
ON this_.Record_Id = Record_Info_.Property_2
WHERE Record_Info_.Record_Info_Id = 
(
    SELECT max(this_0_.Record_Info_Id) as y0_
    FROM Record_Info this_0_
    WHERE this_0_.Property_1 = @p0
    AND this_0_.Property_2 = this_.Record_Id
)

问题是生成的 as y0_,Sybase 不允许我使用的 Sybase 版本的子查询别名。

如何修改我的查询以使 NHibernate 不会为子查询生成别名?

4

1 回答 1

1

我们可以使用自定义 SQL 语句调整子查询的投影。所以而不是:

var subQuery = DetachedCriteria.For<RecordInfo>(); 
    ...
    .SetProjection(Projections.Max("Id")); // instead of this

我们可以完成这个:

var subQuery = DetachedCriteria.For<RecordInfo>(); 
    ...
    .SetProjection(Projections.SqlProjection(" MAX(RecordInfoId) " // use this
      , new string[] {"ID"}
      , new IType[] {NHibernate.NHibernateUtil.Int32}));

我们必须使用列名,因为我们跳过了 NHibernate Property-to-Column ( Idto RecordInfoId)。

这将避免

  • SELECT max(this_0_.Record_Info_Id) as y0_将其替换为
  • SELECT MAX(RecordInfoId)(我们的自定义 SQL)
于 2013-01-30T08:11:32.113 回答