views:

42

answers:

1

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();
    }
}
A: 

Looks like I've found the answer. Not too sure why I didn't think of yesterday, but you can just turn it around and use in.

from Post p
where (
    select t 
    from Tag t 
    where t.Name = :tagName
) in elements(p.Tags)
order by p.DateTime

Easier than I thought. :)

Splash