In this tutorial, you will learn how to add LineItem to the cart within Episerver Commerce 8 In the latest version of Episerver Commerce, a new API has been included called IOrderRepository. This API will allow you do do some pretty useful things with the cart. Want to learn exactly, what you can do, read on 🔥🔥🔥

You can access IOrderRepository using dependency injection,ServiceLocator or Injected<T> (more information on these here). After you have access to the API you can get the cart using the Load<T> method:

When you have access to the cart you can then add a new line item. The line items can be found within OrderForms (as seen on Line 8). To add a line item you also need to add shipping information and the index position to add it. With this data, you can use AddLineItemIndex

Adding A Line Item in Episerver Commerce 7 below

Historically, you could add line items using OrderContext. As OrderContext was not written to an interface, this approach made unit testing your code a pain. The code to add a line item using OrderContext is shown below:

As you can see the process is similar. The main difference is how the cart is accessed!

CartHelper

There is also a helper method that can make life a bit easier when working with the cart called CartHelper. CartHelper provides a set of standard features for the management of carts and orders. CartHelper doesn't use IOrderRepository (at time of writing).

The trade-off with CartHelper is simplicity Vs configurability. CartHelper gives you a simple way to add items to the cart, however, you do not have less control over how items are added. In general, I avoid this API, however, do what makes you happy 😊


You now know how to add a line item into the basket using the new IOrderRepository. I recommend that you favour this technique as it will make unit testing your code simpler. If you can't use the latest version of Episerver Commerce then use OrderContext instead. Happy Coding 🤘