开发者

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 BlogPos开发者_Go百科ts 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜