简体   繁体   中英

NHibernate QueryOver subcollection using Max

I have classes

public class BlogPost
{
    public int Id {get;set;}
    public string Body{get;set;}
    public IList<Comment> Comments{get;set;}
    //other properties
}

public class Comment
{
    public int Id {get;set;}
    public int TypeId {get;set;}
    public int BlogPostId {get;set;}
    public DateTime DateAdd {get;set;}
    public string Body {get;set;}
    //other properties
}

So we have some collection of BlogPost where each BlogPost can have many Comments.

I would like to get collection of all BlogPosts where last Comment (this with MAX(DateAdde) is with TypeId=1 or TypeId=2. Thanks in advance.

I did my best to transpose your class structure into a query I have doing something along the same lines. Mine was after 1 parent with criteria that has a child where the newest child had special criteria. I removed the parent criteria and applied your class structure, so it should be close, but untested.

var query = session.QueryOver<BlogPost>(); //get queryover however you implemented
BlogPost bp = null;
Comment c = null;

var q = QueryOver.Of<BlogPost>(() => bp)
    .JoinAlias(() => bp.Comments, () => c)
    .SelectList(list => list.SelectMax(() => c.DateAdd));

query.JoinQueryOver<Comment>(x => x.Comments)
    .WithSubquery
    .WhereProperty(x => x.DateAdd).Eq(q)
    .Where(x => x.TypeId == 1 || x.TypeId == 2);

     query.List...

Are you using LINQ with NHibernate? How about something like this?

blogPosts.Where(x => x.Comments.Last().TypeId == 1 || x.Comments.Last().TypeId == 2);

I'm not sure if Nhibernate supports nested queries (many ORMs do not), however you might want to try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM