In one of my .NET projects I’m using the NHibernate library for object-relational mapping. I’m mainly using the ICriteria interface to fetch data from the database. Unfortunately I ran into a function that got really complicated; how to query a many-to-many relationship. For example, I have a table containing posts and a table containing tags. The post datamodel contains a set with tags so in my mapping it’s a many-to-many relationship. I want my query to return all posts tagged with one or more specific tags. On this forum I found a solution. I’m not sure if this is the perfect solution, so feel free to suggest a better one.
public IList<Post> GetPostsByTags(IList<Tag> tags) { ICriteria posts = this.Session.CreateCriteria<Post>(); foreach (Tag t in tags) { posts.Add(Subqueries.Exists(DetachedCriteria.For<Post>("p2") .SetProjection(Projections.Id()) .CreateAlias("p2.Tags", "t") .Add(Restrictions.Eq("t.Id", t.Id)) .Add(Restrictions.EqProperty("p2.Id", "this.Id")))); } posts.SetResultTransformer(NHibernate.Transform.Transformers.DistinctRootEntity); return posts.List<Post>(); }