• Publisert
  • 1 min

Creating users from a scheduled task in Commerce

Quick tip if you encounter an "object reference not set to an instance of an object" error while creating users from a scheduled task in EPiServer Commerce

If you are creating EPiServer Commerce users from a scheduled task, you might encounter an "Object reference not set to an instance of an object" error when you call the SaveChanges() on your CustomerContact object.

Fortunately, there is a simple solution to this error. The solution is quite obvious, but I spent too much time finding the solution myself. I thought it would be nice to share the solution in a small blog post :)

The reason you get the error, is that you do not have a DataContext when you are running your scheduled task. Add the following lines in the start of you scheduled task code, and you will be able to create users without any errors:

if (DataContext.Current == null)
{
string connectionstring = ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString;
DataContext.Current = new DataContext(connectionstring);