AI OnAI Off
After some help from support, we found out that the issue was due to the fact, that language is not specified when fetching the commerce item.
By adding a loader option, specifying that the master language should be used, everything seems to work.
See the first line, in the below code:
var catalogItem = _contentRepository.Get<CatalogContentBase>(catalogItemReference, new LoaderOptions() { LanguageLoaderOption.MasterLanguage() });
if (catalogItem != null && catalogItem is EntryContentBase)
{
try
{
var clone = catalogItem.CreateWritableClone<EntryContentBase>();
var unlinkedAssetsDeletedLocal = 0;
var unlinkedAssets = clone.CommerceMediaCollection.Where(x => ContentReference.IsNullOrEmpty(x.AssetLink)).ToList();
foreach(var unlinkedAsset in unlinkedAssets)
{
clone.CommerceMediaCollection.Remove(unlinkedAsset);
}
_contentRepository.Save(clone, SaveAction.Publish, AccessLevel.NoAccess);
}
catch (Exception ex)
{
_logger.Error(nameof(RemoveDeadMediaLinksCommerceJob) + ": " + ex.Message, ex);
}
}
Relevant blog post IContentLoader.Get(contentLink) is considered harmful for catalog content. – Quan Mai's blog (vimvq1987.com)
Hi all
We have built a scheduled job to clear our catalog for "dead links" to assets. The job loops over all entries in our catalog and finds "dead links" and removed these, inspired by this article.
However, we experience, that the "dead links" are not removed in commerce. When debugging, we see the assets being identified and removed from CommerceMediaCollection. When we check commerce UI the assets are still visible with the message "Media not found". If I manually change a random value on the given item in commerce and publish it, everything works fine and the assets are gone.
Below is the code doing the work.
EPiServer CMS v10.10.0.0
EPiServer Commerce v10.7.2.0