Delete association between a catalog items and an asset

Vote:
 

We need to implement functionality where it removes unused asset from the catalog items and then delete an asset permanently. Below is my code, where it goes through each catalog items, and try to remove association when particular asset type is no longer being used. When I execute this code, It's not removing linking between a catalog items and an asset. What could be the cause of this? I have restarted the site and cleared the browser cache, still its not working.

var contentBase = catalogContent.CreateWritableClone<EntryContentBase>();
var commerceMediaCollection = contentBase.CommerceMediaCollection.CreateWritableClone();

foreach (CommerceMedia commerceMedia in commerceMediaCollection)
{
IInRiverAsset resource;
bool success = this._contentLoader.TryGet<IInRiverAsset>(commerceMedia.AssetLink, out resource);
if (success && resource.ResourceAssetType != null && !Enum.TryParse(resource.ResourceAssetType, out assetType))
{
contentBase.CommerceMediaCollection.Remove(commerceMedia);
}
}

this._contentRepository.Save(contentBase, SaveAction.Publish, AccessLevel.NoAccess);

I have applied another route where I have created SQL script, and able to delete asset linking and related data direct from CMS and Commerce SQL databases, and unused asset is not visible in the catalog. I would like to avoid database route. Is there any way to remove asset linking and delete them permanently?

Versions:

Commerce: 13.24.0

CMS: 11.19.0

#245980
Dec 23, 2020 16:37
Vote:
 

The problem is this

var commerceMediaCollection = contentBase.CommerceMediaCollection.CreateWritableClone();

You don't need to clone the media collection, cloning the content is enough

#245995
Dec 23, 2020 21:46
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.