How To Load And Retrieve A Variant or Product From Episerver Commerce

In today's guide, we're going to cover how to get products and variants from Episerver commerce to use on your website.

Getting A Product/Variant Using The Code

If you want to simply get a reference to a product and you know the catalogue or product code, then you can use the ReferenceConverter.

    var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();

    var code = "variant-code"; 
    var variantLink = referenceConverter.GetContentLink(code );

    var repo= ServiceLocator.Current.GetInstance<IContentRepository>();
    var variant= repo.Get<VariationContent>(variantLink );

Getting A Product/Variant Using The Id

If you want to simply get a reference to a product and you only know the Id, you can also do that. Note: You will also need to provide the workId/version Id.

    var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();
    var commerceId = 22;
    var workId = 0;

    var variantLink= referenceConverter.GetContentLink(commerceId , workId);

    var repo= ServiceLocator.Current.GetInstance<IContentRepository>();
    var variant= repo.Get<VariationContent>(variantLink );

Getting the entry Id from a content link

    var contentReference = new ContentReference(4);

    var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();
    var entryId = referenceConverter.GetObjectId(contentReference);

Conclusion

In today's guide, we've covered the different ways of retrieving products or variants from Episerver commerce via the API. All products and variants have a unique code, sometimes known as an SKU, that is associated with it. If you know this you can find a product via the code. Like Episerver CMS you can also use the Id to look up a product. In these instances, you will also need to add the version/work id for the content you want. By default, if you use this it should work in the majority of situations.


Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge


Back to top
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-35662136-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();