Hello Sitecorians! 👋
Welcome to another exciting blog!
In Sitecore Content Hub, assets are often grouped into collections, for example a collection for a campaign. The collection already has metadata like brand, category and campaign name, and in most cases the assets inside it need the same values.
In our project, the business wanted these values to be copied from the collection to its assets automatically, so users don't have to tag every asset by hand and the tagging stays consistent.
In this blog, we will see how to sync collection metadata to asset metadata using an action script and triggers, and which rules we followed to keep the existing asset metadata safe.
So, let's get started! 😊
Why It Matters for the Business
Good tags are what make a DAM useful. Copying metadata from the collection helps in a few ways:
Business need | How it helps |
|---|---|
Findability | Every asset in the collection gets the collection's brand, category and product tags, so search filters and facets actually return them. |
Consistency | The values come from one place (the collection), so you don't get "Brand A" on one asset and a typo on the next. |
Less manual work | Users tag the collection once instead of tagging every asset. Bulk uploads need far less manual tagging. |
And because the rules only fill empty fields, users stay in control: anything they tag on the asset itself is never overwritten.
The Use Case
When an asset is added to a collection, or when a collection's metadata changes, copy the collection's metadata to its assets, but only into fields that are still empty.
We don't do this for every collection, only for collections of a specific Collection type, in this example Campaign. Both the collection and the asset have matching fields. Some are plain properties and some are taxonomy relations:
Collection ( | Asset ( | Kind |
|---|---|---|
|
| Property (text) |
|
| Property (text) |
|
| Property (text) |
|
| Property (multi-value) |
|
| Taxonomy relation |
|
| Taxonomy relation |
|
| Taxonomy relation |
|
| Taxonomy relation |
Example: the campaign collection Summer Campaign 2026 has Brand = Brand A, Category = Hair Care and Language = English. A designer uploads 40 new images into it. Without any manual tagging, all 40 images get Brand A, Hair Care and English. One image that the designer had already tagged with Category = Skin Care keeps Skin Care.
Note: The field names and the Campaign collection type are examples. Use the fields from your own schema; the pattern is the same.
The Business Rules
Copying metadata blindly can do more harm than good. Agree on these rules with the business before you write any code. They are what make the sync safe:
# | Rule | Why |
|---|---|---|
1 | Only fill empty fields. If the asset already has a value, keep it. | Users' own tagging always wins. The sync never overwrites someone's work. |
2 | Only collections of the chosen type (here: Campaign). Other collections, such as personal favourites, are ignored. | A personal collection says nothing about what the asset is. |
3 | Only active assets. For example assets in status Created or Approved, not Archived or Rejected. | Don't touch assets that are on their way out. |
4 | One collection at a time. If an asset is added to several collections in one save, skip the sync for that save. | Two collections may have different brands. Picking one at random would tag the asset wrong. |
5 | Save only when something changed. | Every save fires other triggers and adds load. No change, no save. |
Rule 1 is the most important one for the business: it is what makes users trust the automation.
How It Works
Metadata can need copying from two directions, so the same script has two modes:
- Asset mode. An asset is linked to a collection, from the upload page or the asset's details page, so the asset is saved. A pre-commit step records which collection IDs were just added, and the script copies metadata from those collections only to this one asset.
- Collection mode. A collection's metadata is changed, so the collection is saved. The script copies the collection's metadata to all its active assets, still filling only empty fields.
One script with two modes means the copy rules live in one place and can't drift apart.
Step 1: Keep the Field Mapping in One Place
Start the action script with the mapping, written as simple lists of pairs. When the business asks for one more field to be copied later, it's a one-line change.
// Collection property -> asset property
var propertyMap = new (string From, string To, bool IsMultiValue)[]
{
("CampaignName", "CampaignName", false),
("Owner", "Owner", false),
("Contact", "Contact", false),
("Keywords", "Keywords", true),
};
// Collection relation -> asset relation (same taxonomy on both sides)
var relationMap = new (string From, string To)[]
{
("BrandToCollection", "BrandToAsset"),
("CategoryToCollection", "CategoryToAsset"),
("ProductLineToCollection", "ProductLineToAsset"),
("LanguageToCollection", "LanguageToAsset"),
};Build the load configurations from the same lists, so you only ever load the members you copy:
var collectionLoad = new EntityLoadConfiguration(CultureLoadOption.Default,
new PropertyLoadOption(propertyMap.Select(m => m.From).Append("CollectionType")),
new RelationLoadOption(relationMap.Select(m => m.From).Append("CollectionToAsset")));
var assetLoad = new EntityLoadConfiguration(CultureLoadOption.Default,
new PropertyLoadOption(propertyMap.Select(m => m.To)),
new RelationLoadOption(relationMap.Select(m => m.To).Append("CollectionToAsset").Append("FinalLifeCycleStatusToAsset")));Step 2: Write the "Fill Only If Empty" Helpers
These two small helpers carry rule 1. Each returns true when it changed something, so the script knows whether the asset needs saving.
bool CopyProperty(IEntity collection, IEntity asset, string from, string to, bool isMultiValue)
{
if (isMultiValue)
{
var source = collection.GetPropertyValue<string[]>(from);
var current = asset.GetPropertyValue<string[]>(to);
if (source == null || source.Length == 0) return false; // nothing to copy
if (current != null && current.Length > 0) return false; // asset already tagged: keep it
asset.SetPropertyValue(to, source);
return true;
}
var value = collection.GetPropertyValue<string>(from);
if (string.IsNullOrEmpty(value)) return false;
if (!string.IsNullOrEmpty(asset.GetPropertyValue<string>(to))) return false;
asset.SetPropertyValue(to, value);
return true;
}
bool CopyRelation(IEntity collection, IEntity asset, string from, string to)
{
var sourceIds = collection.GetRelation(from).GetIds();
var assetRelation = asset.GetRelation(to);
if (!sourceIds.Any()) return false;
if (assetRelation.GetIds().Any()) return false; // asset already tagged: keep it
assetRelation.SetIds(sourceIds);
return true;
}"Empty" means the whole field. If the asset already has one brand and the collection has another, we don't add the second one. Merging values sounds helpful, but it quietly turns a correct tag into a wrong combination. Keep it simple: empty gets filled, anything else stays.
Step 3: Write the Copy Script for Both Modes
The main body decides which mode it is in from the entity that triggered it, builds two lists (the collections to copy from and the assets to copy to), and then runs the same loop for both.
const string SyncCollectionType = "Campaign";
var target = Context.Target as IEntity;
if (target?.Id == null) return;
var allowedStatusIds = new[]
{
(await MClient.Entities.GetAsync("M.Final.LifeCycle.Status.Created")).Id.Value,
(await MClient.Entities.GetAsync("M.Final.LifeCycle.Status.Approved")).Id.Value
};
var collections = new List<IEntity>();
var assets = new List<IEntity>();
if (target.DefinitionName == "M.Asset")
{
// ASSET MODE: copy from the collection(s) this asset was just added to
await target.LoadMembersAsync(assetLoad.PropertyLoadOption, assetLoad.RelationLoadOption);
var status = target.GetRelation<IChildToOneParentRelation>("FinalLifeCycleStatusToAsset").Parent;
if (status == null || !allowedStatusIds.Contains(status.Value)) return; // rule 3
var addedIds = ReadIdsFromPropertyBag("addedCollectionIds"); // written in pre-commit
if (addedIds.Count == 0) return;
if (addedIds.Count > 1) { MClient.Logger.Info("Added to several collections at once, skipping"); return; } // rule 4
collections.AddRange(await MClient.Entities.GetManyAsync(addedIds, collectionLoad));
assets.Add(target);
}
else
{
// COLLECTION MODE: copy from this collection to all its active assets
await target.LoadMembersAsync(collectionLoad.PropertyLoadOption, collectionLoad.RelationLoadOption);
collections.Add(target);
assets.AddRange(await GetActiveAssetsOfCollectionAsync(target.Id.Value, allowedStatusIds)); // paged, see below
}
foreach (var collection in collections.Where(c => c.GetPropertyValue<string>("CollectionType") == SyncCollectionType)) // rule 2
{
foreach (var asset in assets)
{
var changed = false;
foreach (var m in propertyMap) changed |= CopyProperty(collection, asset, m.From, m.To, m.IsMultiValue);
foreach (var m in relationMap) changed |= CopyRelation(collection, asset, m.From, m.To);
if (changed) await MClient.Entities.SaveAsync(asset); // rule 5
}
}In collection mode, a collection can hold thousands of assets, so page through them instead of loading them in one query. Content Hub's search-after query is a good fit:
async Task<List<IEntity>> GetActiveAssetsOfCollectionAsync(long collectionId, long[] statusIds)
{
var filter = QueryFilterBuilder.Definition.Name == "M.Asset"
&& QueryFilterBuilder.Parent("CollectionToAsset").Id == collectionId
&& (QueryFilterBuilder.Parent("FinalLifeCycleStatusToAsset").Id == statusIds[0]
|| QueryFilterBuilder.Parent("FinalLifeCycleStatusToAsset").Id == statusIds[1]);
var query = new SearchAfterQuery(filter,
new List<Sorting> { new() { Field = "identifier", Order = QuerySortOrder.Desc } })
{ Take = 50, LoadConfiguration = assetLoad };
var result = await MClient.Querying.SearchAfterAsync(query);
var all = new List<IEntity>(result.Items);
while (all.Count < result.TotalItems && result.Items.Any())
{
query.SearchAfter = result.LastHitData;
result = await MClient.Querying.SearchAfterAsync(query);
all.AddRange(result.Items);
}
return all;
}Don't forget the paging. A plain query without paging only returns the first page of results. On a big collection, the sync would then quietly skip most of the assets, and nobody would notice until someone searches for them.
Step 4: Wire It Up With Triggers
In asset mode the script needs to know which collections were just added. After the save is committed, that information is gone, so a tiny pre-commit script records it in the property bag, which Content Hub hands to the post-commit actions of the same save:
// Pre-commit action script on M.Asset
var added = Context.ChangeTracker.GetNewIds("CollectionToAsset", RelationRole.Child);
if (added?.Any() == true)
Context.PropertyBag["addedCollectionIds"] = string.Join(",", added);And the helper the copy script uses to read it back:
List<long> ReadIdsFromPropertyBag(string key) =>
Context.PropertyBag.TryGetValue(key, out var value) && !string.IsNullOrEmpty(value)
? value.Split(',').Select(long.Parse).ToList()
: new List<long>();Then create the actions and triggers in Manage → Actions and Manage → Triggers:
Trigger | Objective | Conditions | Actions |
|---|---|---|---|
Asset added to collection | Entity creation and modification, in process | Definition is | Pre-commit: the script above. Post-commit: the copy script |
Collection metadata changed | Entity modification, out of process | Definition is | Post-commit: the copy script |
No endless loops: The copy script saves assets, which could fire asset triggers again. That's fine here, because the asset trigger only fires when
CollectionToAssetchanges, and the copy script never changes that relation. Keep it that way when you add new fields to the mapping.
Step 5: Handle Fields That Use a Different Taxonomy
Not every field maps one to one. In our case, collections use a Geography taxonomy, while assets use a separate Asset Geography taxonomy with the same values. You can't copy the IDs, because they point to different entities. Instead, map by value:
- Read the geography IDs on the collection.
- For each one, load its
ClassificationName(for example Europe). - Find the Asset Geography item with the same name.
- Add that ID to the asset's geography relation, again only if the asset has no geography yet.
async Task<long?> MapToAssetGeographyAsync(long geographyId)
{
var geo = await MClient.Entities.GetAsync(geographyId,
new EntityLoadConfiguration(CultureLoadOption.Default, new PropertyLoadOption("ClassificationName"), RelationLoadOption.None));
var name = geo?.GetPropertyValue<string>("ClassificationName");
if (string.IsNullOrEmpty(name)) return null;
var query = Query.CreateIdsQuery(entities => from e in entities
where e.DefinitionName == "AssetGeography" && e.Property("TaxonomyName") == name
select e);
return await MClient.Querying.SingleIdAsync(query); // null = no match, log it
}Log every value that can't be mapped. If a collection has a geography that doesn't exist in the asset taxonomy, the asset silently stays untagged. A clear log line tells the taxonomy owners exactly which value to add.
It's Working! 🎉
Create a test collection of type Campaign with Brand, Category and Language filled in, and walk through each rule:
Test | Expected result |
|---|---|
Upload a new, untagged asset into the collection | The asset gets the collection's Brand, Category and Language |
Upload an asset with Category already set to something else | Its own Category stays; the other empty fields are filled (rule 1) |
Add an asset to a collection of another type, such as a personal collection | Nothing is copied (rule 2) |
Add an archived asset to the collection | Nothing is copied (rule 3) |
Add one asset to two collections in the same save | Nothing is copied, and the log says why (rule 4) |
Change the collection's Category while some assets have no Category | Those assets get the new Category; assets that already had one keep it |
Use a collection with more than 50 assets | All assets are updated, not only the first page |
You can follow each run in Manage → Scripts → your copy script → Logs.
Verify the Sync With GraphQL
The UI shows the result, but GraphQL shows the before and after side by side, which makes it easy to prove the sync worked. I used the GraphQL IDE of the delivery platform (Experience Edge). The Preview API works the same way.
Note: GraphQL only returns definitions and members that are published to the delivery platform. If a field is missing from the schema, publish it first in Manage → Delivery platform.
1. The collection (the source). Check which values the collection has:
query CollectionMetadata {
m_Collection(id: "<collection identifier>") {
id
collectionName
collectionType
brandToCollection { results { id classificationName } }
categoryToCollection { results { id classificationName } }
languageToCollection { results { id classificationName } }
}
}
2. The asset before it is linked. Upload an asset outside the collection and query it. The fields are empty:
query Asset {
m_Asset(id: "<asset identifier>") {
id
title
brandToAsset { results { classificationName } }
categoryToAsset { results { classificationName } }
languageToAsset { results { classificationName } }
}
}{
"data": {
"m_Asset": {
"id": "<asset identifier>",
"title": "test collection image 1.jpeg",
"brandToAsset": { "results": [] },
"categoryToAsset": { "results": [] },
"languageToAsset": { "results": [] }
}
}
}3. The collection's assets after linking. Add the asset to the collection (or upload it straight into the collection), wait a few seconds, and query the collection's assets:
query CollectionAssets {
m_Collection(id: "<collection identifier>") {
collectionName
collectionToAsset(first: 5) {
results {
id
title
brandToAsset { results { id classificationName } }
categoryToAsset { results { id classificationName } }
languageToAsset { results { id classificationName } }
}
}
}
}The asset now carries the collection's values:
{
"data": {
"m_Collection": {
"collectionName": "TEST COLLECTION",
"collectionToAsset": {
"results": [
{
"id": "<asset identifier>",
"title": "test collection image 1.jpeg",
"brandToAsset": { "results": [ { "id": "<brand id>", "classificationName": "test" } ] },
"categoryToAsset": { "results": [ { "id": "<category id>", "classificationName": "<category name>" } ] },
"languageToAsset": { "results": [ { "id": "<language id>", "classificationName": "English" } ] }
}
]
}
}
}
}Tip: Field names in GraphQL start with a lower-case letter and follow your schema, so a relation called
BrandToAssetin Content Hub becomesbrandToAsset. Use the IDE's autocomplete (Ctrl+Space) or the Schema tab to find the exact names in your instance.
Conclusion
Syncing collection metadata to its assets makes the collection the single place where tags are entered, and every asset in it benefits automatically. The technical part is small: one mapping, two "fill only if empty" helpers, one script with an asset mode and a collection mode, and two triggers. The real value is in the business rules: never overwrite what users tagged, only use the right type of collection, only touch active assets, and skip when the source is ambiguous. Agree on those first, and the business gets better-tagged assets with less effort.
I hope this helps you in your Content Hub journey! If you have any questions, feel free to drop a comment below. 😊
Stay tuned for more! 👋



