Just sharing some of my inconsequential lunch conversations with you... RSS  

Thursday, December 27, 2007

Querying Many To Many associations using the Criteria API

Ayende as just posted about querying many to many associations using Criteria. Here's how:

DetachedCriteria blogAuthorIsJosh = DetachedCriteria.For<User>()
.Add(Expression.Eq("Username", "josh")
.CreateCriteria("Blogs", "userBlog")
.SetProjection( Projections.Id())
.Add(Property.ForName("userBlog.id").EqProperty("blog.id"));

DetachedCriteria categoryIsNh = DetachedCriteria.For(typeof(Category),"category")
.SetProjection(Projections.Id())
.Add(Expression.Eq("Name", "NHibernate"))
.Add(Property.ForName("category.id").EqProperty("postCategory.id "));

session.CreateCriteria(typeof (Post),"post")
.CreateAlias("Categories", "postCategory")
.Add(Subqueries.Exists(categoryIsNh))
.CreateAlias("Comments", "comment")
.Add(Expression.Eq("comment.Name", "ayende"))
.CreateAlias("Blog", "blog")
.Add(Subqueries.Exists(blogAuthorIsJosh))
.List();

I had already tried it but with no results. Looks like a refactoring week is approaching for me if I can get it to work over our HBMs :)

No comments:

Development Catharsis :: Copyright 2006 Mário Romano