If you are using Episerver Commerce (or should I say, Optimizely B2C Commerce), you will, at some point, need to get the contact by an email address. That sounds like an easy enough task, until you realize that the class to manage customer contacts –CustomerContext
has no such method. You will need to find another way, and this is one way you can do it
CustomerContact contact = customerContext.GetContacts().Where(m => m.Email == email)?.FirstOrDefault();
Of course this is not the optimal – avoid it if you can. First of all it loads a lot of contact just to find one. Also while it looks like you are getting all contacts (which is of course something to avoid), you are only get the first 1000 contacts by default, so the code above would return inaccurate result.
Is there a better way?
Yes of course.
Contact was built on “Business Foundation” – think of it as an ORM with extensions. Business Foundation allows great flexibility, with a few caveats. This is how you can find contact by email address:
try
{
var filterEl = new FilterElement("Email", FilterElementType.Equal, email);
return
BusinessManager.List(ContactEntity.ClassName, new[] { filterEl })
.OfType<CustomerContact>()
.FirstOrDefault();
}
catch (ObjectNotFoundException)
{
//Safe guard
return null;
}
BusinessManager
does not have a Get
method, so we are use List
instead. Note that Email
is supposed to be unique, so this should not have any down side with performance (see note below).
This is not limited to email, or to contact. You can find contacts by other properties, or get an Organization with same technique.
It is very important to note, however, this need a proper index on Contact tables, to make sure you are not killing your database.