I have previously written about how to extend the LineItem class in this article Adding Custom MetaData to the LineItem Class in Episerver Commerce via Code
I had a question recently about how to do the same thing for the Cart. The code to add a custom property is very similar as adding a property to the Lineitem class, the only difference being the class you get from OrderContext.Current. When working with Line items we use OrderContext.Current.PurchaseOrderMetaClass and when we work with the cart we OrderContext.Current.ShoppingCartMetaClass. This is exactly the same as if you want to extend Order Form, Order Address, Order Item or Payment Plan. use the same code snippet as below, but swap the use the typeReference with the class that you want to extend. You can then use the classes CreateField method to add your custom property.
The cart code will look like this:
using Mediachase.Commerce.Orders; var typeReference = OrderContext.Current.ShoppingCartMetaClass; var context = OrderContext.MetaDataContext; var name = "CustomProperty"; var displayName = "Custom Property"; var length = 256; var metaFieldType = MetaDataType.LongString; var metaNamespace = string.Empty; var description = string.Empty; var isNullable = false; var isMultiLanguage = true; var isSearchable = true; var isEncrypted = true; var metaField = MetaField.Create(context , metaNamespace, name, displayName, description, metaFieldType, length, isNullable, isMultiLanguage, isSearchable, isEncrypted); cartClassTypeReference.AddField(metaField);
You can then access your property using the following code:
var cart= orderRepository.Load<Cart>("Customer Id", Cart.DefaultName).FirstOrDefault(); cart[CustomProperty] = "Setting"; var customProperty = cart[CustomProperty] as string;
Today, we’ve talked about how to modify the code to add a custom property to the lineItem class to now work on the cart class. The process for all the commerce objects is all very similar, you useOrderContext.Current to find the class that you want to modify, define a custom MetaField then use the AddField method to store it to the database.