In this tutorial, you will learn how to extend the Episerver Commerce LineItem object. When we work with the basket in Episerver commerce, it is quite likely you may need to store some custom data against a line item. Extra data could include an image of the product, or if a discount or offer is currently available on it. It is possible to update the line item object both within the commerce admin UI and in code. In this tutorial, we will follow the code approach.

Following a code-first update strategy, you will need to look in the Mediachase.Commerce.Orders namespace for OrderContext.Current.PurchaseOrderMetaClass and OrderContext.MetaDataContext. You can use these helpers to get access to the class definition. Using MetaField.Create() you can then add whatever extra properties you want to the line item object!

When I start a new commerce build, I typically like to configure the whole Episerver and Episerver commerce database in code. This means that when a developer pulls the code, builds the solution and runs it, their local database will be set up automatically. Having the ability to trash your database and re-build it can be very useful for development.

In this scenario, I will show you how to add an extra property, which will be called Custom Property, onto the LineItem class. This can be done using the commerce metadata plus API. Using this API and the OrderContext you can add as many custom properties as you want against LineItems. The code to do this is shown below:

I've simplified this code snippet to make it easier to read. First, we use OrderContext.Current.PurchaseOrderMetaClass to get the MetaClass. This is the class that we will save our new property against. Next, we use OrderContext.MetaDataContext to get the MetadataContext. After that, we call MetaField to create the property and then metaClass.AddField to save it. You can then access your property using the following snippet:

That's it... Happy Coding 🤘