Reputation: 1601
I am retrieving the customer id from CRM 2011. I am working with the Campaign Response Entity, but it is something that applies with any other Entity containing a Customer lookup.
The only way I found so far is this one:
var customerGuid =
((EntityReference)
((EntityCollection) ebCampaignResponse.Entity.Attributes["customer"]).Entities[0]
.Attributes["partyid"]).Id;
I think it is way too complicate and that I am missing something. Is there any better way to do it?
IMPROVED CODE:
var customerGuid = Guid.Empty;
EntityCollection customer = null;
if (ebCampaignResponse.Entity != null && ebCampaign.Entity.Contains("customer"))
customer = (EntityCollection) ebCampaignResponse.Entity.Attributes["customer"];
if(customer != null && customer.Entities != null && customer.Entities[0] != null)
customerGuid = ((EntityReference)(customer.Entities[0]
.Attributes["partyid"])).Id;
Upvotes: 0
Views: 729
Reputation: 886
Your code is prone to errors if the customer attribute is null; though the way you are retrieving it is correct but a more cleaner way I would prefer this to be done is as follows
var customer = ebCampaignResponse.Entity.GetAttributeValue<EntityCollection>("customer").Entities.FirstOrDefault();
if(customer != null) {
var customerGuid = customer.GetAttributeValue<EntityReference>("partyid").Id;
}
PS I doubt there is an attribute called customer
in the response, I think it should be customers
. Also, the above code that I included might also throw errors, all I did is formatted your code and showed you a neater way to go about it.
OR (if you don't like the first approach)
var customer = ebCampaignResponse.Entity.GetAttributeValue<EntityCollection>("customer").Entities.FirstOrDefault();
if(customer == null) return;
var customerGuid = customer.GetAttributeValue<EntityReference>("partyid").Id;
Upvotes: 2