Search code examples
c#asp.netdynamics-crmdynamics-crm-4

MS Dynamics 4.0: Checking whether record exists based on email address


I'm having trouble with a method that needs to return the GUID of a record based a given email address. This is what I have at the moment:

        ColumnSet columnSet = new ColumnSet();
        columnSet.AddColumns(new[] { "leadid" });

        var query = new QueryExpression
        {
            EntityName = "lead",
            ColumnSet = columnSet
        };

        FilterExpression leadFilter = new FilterExpression();
        leadFilter.AddCondition(new ConditionExpression
        {
            AttributeName = "emailaddress1",
            Operator = ConditionOperator.Equal,
            Values = new object[] { emailAddress }
        });

        query.Criteria = leadFilter;

        BusinessEntityCollection result = crmService.RetrieveMultiple(query);

        foreach (BusinessEntity record in result)
        {
            //Guid leadId = ?? Not sure how to extract it. 
        }

A) this seems like overkill, because I only need one record (but don't think I can use Retrieve because I don't have an id). B) How do I actually retrieve the GUID from the above within the foreach?

Thanks.


Solution

  • A) There's no guarantee that you'll only get one entity back, it might be the case, for example, that there are multiple leads with the same email address.

    B) You can cast the BusinessEntity to the entitype you queried for, it's the abstract base class for all the other entitytypes.