I have entities Post
and Tag
, where there is a many-to-many relationship between the two (e.g. each post can have one or more tags, and each tag can be associated with any number of posts).
What I would like to achieve is to have the Tag
entity to have a field providing the number of posts which are associated with that tag. However, I don't know how to go about getting this without getting the entire collection of Post
s (which I'd like to avoid).
I am using Fluent NHibernate and my entities and mappings look like this currently:
Entities/Post.cs
public class Post : PersistentBase
{
public virtual string Title { get; set; }
/* snip */
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);
}
}
Mappings/PostMap.cs
public class PostMap : ClassMap<Post>
{
public PostMap()
{
Id(x => x.Id).GeneratedBy.HiLo("99");
Map(x => x.Title);
/* snip */
HasManyToMany(x => x.Tags);
}
}
Entities/Tag.cs
public class Tag : PersistentBase
{
public virtual string Name { get; set; }
public static Tag Create(string name) {
return new Tag { Name = name };
}
}
Mappings/TagMap.cs
public class TagMap : ClassMap<Tag>
{
public TagMap ()
{
Id(x => x.Id).GeneratedBy.HiLo("99");
Map(x => x.Name).Unique();
}
}
Ideally what I'd like to achieve is to be able to add into Entities/Tag.cs, something like the following:
public virtual int PostCount { get; set; }
And then have that pre-filled with the number of posts using that tag.
How might I go about doing this? (is it indeed possible?)