In this tutorial, you will learn how to add a custom property to the customer object in Episerver commerce... in code! When building your own commerce system you will need to store custom customer data. Out-of-the-box, Episerver commerce ships with a default customer object that has lots of good useful properties. An enterprise-level e-commerce store will always require a certain level of customization. Maybe you want to store your customer date of birth or newsletter opt-in status. As this is profile data, rather than authentication data, storing this data in the membership provider doesn't make sense. In these situations adding the profile data onto the commerce customer object is a better option. Updating the customer object is possible within the commerce admin UI, however, this can lead to painful database sync issues. Instead, life will be much easier if you define the properties in code and then whenever any of the developers on your team pull the latest code and build the solution, their local databases will automatically be updated as needed 🔥🔥🔥

To get started, you need to call CustomerContact.CreateInstance(membershipUser). If you don't do this and try to call a customer object, Episerver will create two commerce customers which you definitely don't want. In this project, we wanted to unit test a lot of the customer and authentication code, so to make this unit-testable, I have wrapped the code into a wrapper method called CustomerContactHelper. Unfortunately, the default CustomerContact API has not been built against an interface, so you need to do this if you want to use dependency injection. Using a wrapper built that is built to an interface means the dependency can be swapped out in your unit test library using Moq!

After this, you need to update your data into the customer object.  Out of the box commerce comes with a number of default properties like First Name, Last Name but, in my circumstance, there was no default Newsletter opt-in.  Adding a property doesn't involve that much code luckily. 

I wrote an article on in-depth guide how to do this called Adding a custom field into the Commerce Customer Object via code. In essence, you need two things. Some code to get the object:

Some code to create a property:

After you have added all the properties you require to the commerce customer, you then need to call customerContact.SaveChanges() method to persist the changes to the database. I have wrapped the save method in the wrapped I created above so we can unit test this code. We have to wrap this call because if you try to call SaveChanges() within a unit test on its own, you will get an ActivationException. The final thing is to add this code within a Initialization module, so it runs when the site loads!


That's it! You can now create your own commerce customers via code! Happy Coding 🤘