How to query across many-to-many association in NHibernate?
Posted
by Splash
on Stack Overflow
See other posts from Stack Overflow
or by Splash
Published on 2010-03-20T23:33:31Z
Indexed on
2010/03/20
23:41 UTC
Read the original article
Hit count: 214
I have two entities, Post
and Tag
. The Post
entity has a collection of Tags which represents a many-to-many join between the two (that is, each post can have any number of tags and each tag can be associated with any number of posts).
I am trying to retrieve all Posts which have a given tag. However, I seem to be unable to get this query right. I essentially want something which means the same as the following pseudo-HQL:
from Posts p
where p.Tags contains (from Tags t where t.Name = :tagName)
order by p.DateTime
The only thing I've found which even approaches this is a post by Ayende. However, his approach requires the entity on the other side (in my case, Tag
) to have a collection showing the other end of the many-to-many. I don't have this and don't really wish to have it. I find it hard to believe this can't be done. What am I missing?
My entities & mappings look like this (simplified):
public class Post {
public virtual int Id { get; set; }
public virtual string Title { get; set; }
private IList<Tag> tags = new List<Tag>();
public virtual IEnumerable<Tag> Tags {
get { return tags; }
}
public virtual void AddTag(Tag tag) {
this.tags.Add(tag);
}
}
public class PostMap : ClassMap<Post> {
public PostMap() {
Id(x => x.Id).GeneratedBy.HiLo("99");
Map(x => x.Title);
HasManyToMany(x => x.Tags);
}
}
// ----
public class Tag {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class TagMap : ClassMap<Tag> {
public TagMap () {
Id(x => x.Id).GeneratedBy.HiLo("99");
Map(x => x.Name).Unique();
}
}
© Stack Overflow or respective owner