Somehow i was able to find solution for this issue. Here is the solution using plugin. In the below function i have used QueryExpression to find the Contact and Lead matching the email address provided in the input parameter to the method.
// calling GetRelatedEntity method in main Execute method.
if (entity.LogicalName == "new_eventregistration")
{
if (entity.Attributes.Contains("new_email"))
{ eventRegEmail = entity.Attributes["new_email"].ToString();
// To check the Contact for matching email address
#region contact lookup
EntityCollection ContactsEC = GetRelatedEntity(orgService, "contact", "emailaddress1", eventRegEmail, new ColumnSet("fullname", "contactid","emailaddress1"));
if (ContactsEC.Entities.Count >= 1)
{ entity.Attributes["new_relatedcontact"] = new EntityReference("contact", ContactsEC.Entities[0].Id) ; // setting the reference of contact to Event Registration - Related Contact field
}
#endregion contact lookup
#region lead lookup
else {
EntityCollection LeadsEC = GetRelatedEntity(orgService, "lead", "emailaddress1", eventRegEmail, new ColumnSet("fullname", "leadid", "companyname"));
if (LeadsEC.Entities.Count >= 1)
{ // setting the reference of contact to Event Registration - Related Lead field
entity.Attributes["new_relatedlead"] = new EntityReference("lead", LeadsEC.Entities[0].Id);}
}
#endregion lead lookup
}
}
// Generic method to query Contact and lead based on the parameters supplied
private static EntityCollection GetRelatedEntity(IOrganizationService orgSvc, string entityName, string searchItem, string searchItemValue, ColumnSet colSet)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = colSet,
Criteria = new FilterExpression
{
Conditions ={
new ConditionExpression{
AttributeName = searchItem,
Operator = ConditionOperator.Equal,
Values = { searchItemValue }
}
}
}
}; return orgSvc.RetrieveMultiple(query);
}
#endregion lookup method
}