private async Task UpsertSellableItem(SellableItem item, CommercePipelineExecutionContext context) { if (string.IsNullOrEmpty(item.ProductId)) { item.ProductId = item.Id.SimplifyEntityName().ProposeValidId(); } if (string.IsNullOrEmpty(item.FriendlyId)) { item.FriendlyId = item.Id.SimplifyEntityName(); } if (string.IsNullOrEmpty(item.SitecoreId)) { item.SitecoreId = GuidUtility.GetDeterministicGuidString(item.Id); } CommerceEntity entity = await _findEntityPipeline .Run(new FindEntityArgument(typeof(SellableItem), item.Id), context) .ConfigureAwait(false); if (entity == null) { await _persistEntityPipeline.Run(new PersistEntityArgument(item), context).ConfigureAwait(false); return; } if (!(entity is SellableItem)) { return; } var existingSellableItem = entity as SellableItem; // Try to merge the items. existingSellableItem.Name = item.Name; foreach (Policy policy in item.EntityPolicies) { if (existingSellableItem.HasPolicy(policy.GetType())) { existingSellableItem.RemovePolicy(policy.GetType()); } existingSellableItem.SetPolicy(policy); } if (item.HasComponent <ItemVariationsComponent>()) { var variations = existingSellableItem.GetComponent <ItemVariationsComponent>(); foreach (ItemVariationComponent variation in item .GetComponent <ItemVariationsComponent>().ChildComponents .OfType <ItemVariationComponent>()) { ItemVariationComponent existingVariation = existingSellableItem.GetVariation(variation.Id); if (existingVariation != null) { existingVariation.Name = variation.Name; foreach (Policy policy in variation.Policies) { if (existingVariation.Policies.Any(x => x.GetType() == policy.GetType())) { existingVariation.RemovePolicy(policy.GetType()); } existingVariation.SetPolicy(policy); } } else { variations.ChildComponents.Add(variation); } } } await _persistEntityPipeline.Run(new PersistEntityArgument(existingSellableItem), context).ConfigureAwait(false); }