Tagging a fake Orchard content item
In my series of posts about building fake Orchard content items for testing purposes, here’s a short one that shows how to add tags to a fake content item. This one is interesting because it shows a basic case of relationship (between the item and its tags). The way tags have been implemented (it’s one of the oldest modules in Orchard, and one that should honestly be replaced with taxonomies in almost all cases), in order to add tags, we’ll need to create records for each:
public static class TagsHelper {
public static void AddTags(IContent item, params string[] tags) {
var tagsPart = new TagsPart {
Record = new TagsPartRecord {
Tags = tags.Select(tag => new ContentTagRecord {
TagRecord = new TagRecord {
TagName = tag
}
}).ToList()
}
};
item.ContentItem.Weld(tagsPart);
}
}
This little helper just creates a tags part, then one relationship record per tag (ContentTagRecord), pointing to corresponding tag records. In a real database, tag records can be used by more than one item, which is why we need the relationship records, but for testing, it’s most of the time ok to create new tag records very time.
The helper can be used as follows:
var item = ContentHelpers.PrepareItem("TestType", 1);
TagsHelper.AddTags(item, "tag1", "tag2", "tag3");
The code for the ContentHelpers class can be found here. I’m using an additional method here that build a basic item without any additional parts beyond the Infoset:
public static ContentItem PrepareItem(string contentType, int id = -1) {
var infosetPart = new InfosetPart();
var contentItem = infosetPart.ContentItem = new ContentItem {
VersionRecord = new ContentItemVersionRecord {
ContentItemRecord = new ContentItemRecord()
},
ContentType = contentType
};
contentItem.Record.Id = id;
contentItem.Weld(infosetPart);
StubContentManager.AddTo(contentItem);
return contentItem;
}
Next time, I may show how to add a fake taxonomy to a fake item, which is insanely more difficult.