As written before, there is a IDeleteRelationshipPipeline to remove the relation, but you are most probably struggling with getting the Category ids, that the SellableItem relates to, to remove the relations. The relation is stored in ParentCategoryList of the SellableItems, but this list contains Sitecore item ids, and not the Commerce entity ids. So you have to find a Commerce entity ids for each of the categories.
I do it like this:
public async Task UpsertSellableItemCategories(ProductModel product, CommercePipelineExecutionContext context)
{
var entity = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), $"{CommerceEntity.IdPrefix<SellableItem>()}{product.Id}"), context);
if (entity == null)
{
return;
}
if (!(entity is SellableItem))
{
return;
}
var existingSellableItem = entity as SellableItem;
var categoryIds = existingSellableItem?.ParentCategoryList?.Split('|');
//Get all existing categories
var categoryList = await _getManagedListPipeline.Run(new FindEntitiesInListArgument(typeof(Category), CommerceEntity.ListName<Category>(), 0, int.MaxValue), context);
var lst = categoryList.List.Items.Cast<Category>();
if (categoryIds != null)
{
//For each already related category
foreach (var categoryId in categoryIds)
{
Category category = null;
foreach (var cat in lst)
{
if (cat.SitecoreId == categoryId)
{
category = cat;
break;
}
}
if (category != null)
{
//If category should not be related
if (!product.Categories.ContainsKey(category.FriendlyId))
{
//remove relationship
await this._deleteRelationshipPipeline.Run(
new RelationshipArgument(
category.Id,
$"{CommerceEntity.IdPrefix<SellableItem>()}{product.Id}",
ProductConstants.RelationDefinitions.CategoryToSellableItem
)
{
Mode = new RelationshipMode?(RelationshipMode.Delete)
}, context);
}
else //If category should still be related
{
//relationship exits, don't add again
product.Categories.Remove(category.FriendlyId);
}
}
}
}
foreach (var cat in lst)
{
if (product.Categories.ContainsKey(cat.FriendlyId)) //contains only new categories
{
await this._createRelationshipPipeline.Run(
new RelationshipArgument(
cat.Id,
$"{CommerceEntity.IdPrefix<SellableItem>()}{product.Id}",
ProductConstants.RelationDefinitions.CategoryToSellableItem
)
{
Mode = new RelationshipMode?(RelationshipMode.Create)
}, context);
}
}
}
- I have a list of the new categories in my ProductModel.Categories, that the SellableItem relates to.
- First I remove relation to the ones that are not in the list III
- I add the new relations