开发者

NHibernate: How to use "IN" with CreateCriteria?

开发者 https://www.devze.com 2022-12-12 16:17 出处:网络
I have a parent-child table relationship: Elements -(1 to n)-> ContentBlocks.Each ContentBlock row has:unique Id (Id), ElementId, Version, and then some less relevant fields.I\'m trying to get all Con

I have a parent-child table relationship: Elements -(1 to n)-> ContentBlocks. Each ContentBlock row has: unique Id (Id), ElementId, Version, and then some less relevant fields. I'm trying to get all Content rows that have the highest Version number (and Id) on them.

I have this line of SQL that gives me what I want:

SELECT * FROM ContentBlocks WHERE Id IN 
    (SELECT MAX(Id) FROM ContentBlocks GROUP BY ElementId)

(this assumes that the latest version has the highest Id)

However, I can't figure out how to get it from NHibernate. This is the closest I've gotten:

var subquery = DetachedCriteria.For<ContentBlock>()
            .SetProjection( Projections.Max( "Id" ) )
            .SetProjection( Projections.GroupProperty( "ElementId" ) );

var query = session.CreateCriteria<ContentBlock>()
            .Add( Subqueries.PropertyIn( "Id", subquery ) ).List<ContentBlock>();

If I execute subquery, I get a list of the unique ElementIds in the table. Instead, I need the list of Ids of the newest ContentBlocks. If I reverse the order of the SetProjections on the subquery, I just get the max of ElementId.

I also tried this way:

        subquery = DetachedCriteria.For<ContentBlock>()
            .Se开发者_如何学GotProjection(
                Projections.ProjectionList()
                    .Add( Projections.Max( "Id" ) )
                    .Add( Projections.GroupProperty( "ElementId" ) )
                );

but that gets me a list of arrays with 2 elements in it, Id & ElementId, which the CreateCriteria call can't process.

Is there a way to not include the Grouped Property "ElementId" in the results? Or specify that I want to return Max(Id) instead?


Not implemented yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消