我正在从CRM 2011检索客户id。我正在与市场活动响应实体合作,但它适用于任何其他包含客户查询的实体。
到目前为止,我找到的唯一方法是:
var customerGuid =
((EntityReference)
((EntityCollection) ebCampaignResponse.Entity.Attributes["customer"]).Entities[0]
.Attributes["partyid"]).Id;
我觉得这太复杂了,我错过了一些东西。有更好的方法吗?
改进代码:
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;
如果customer属性为null,您的代码很容易出错;虽然你检索它的方式是正确的,但我更喜欢这样做的一种更干净的方式是如下
var customer = ebCampaignResponse.Entity.GetAttributeValue<EntityCollection>("customer").Entities.FirstOrDefault();
if(customer != null) {
var customerGuid = customer.GetAttributeValue<EntityReference>("partyid").Id;
}
PS我怀疑响应中是否有一个名为customer
的属性,我认为应该是customers
。此外,我包含的上述代码也可能会出现错误,我所做的只是格式化你的代码,并向你展示了一种更整洁的方法
或者(如果你不喜欢第一种方法)
var customer = ebCampaignResponse.Entity.GetAttributeValue<EntityCollection>("customer").Entities.FirstOrDefault();
if(customer == null) return;
var customerGuid = customer.GetAttributeValue<EntityReference>("partyid").Id;