Issues with EntityReference in Plugin RRS feed

  • Question

  • I'm not sure what I am doing wrong here. I have used this code over and over again on other plugins with no issues. I'm practically copy pasting code that works and only changing the field names.

    Anyway I am getting an error message "Unable to cast object of type Microsoft.Xrm.Sdk.EntityCollection" to type "Microsoft.Xrm.Sdk.EntityReference".

    The bolded line seems to be causing the issue. But maybe I'm wrong. Can anyone see what I'm doing wrong this time? Thanks!

    [edit] This plugin runs on phone call create. So that when a quick campaign is created and all the phone calls are displayed the state of the account is on the phone call record and we can sort by state to assign out the calls. I'm not sure if the [to] field is what's causing the issue? But I've used the same code for customerid off of the Case entity and it works fine.

    Entity entity = (Entity)context.InputParameters["Target"];
                    EntityReference accountId = (EntityReference)entity.Attributes["to"];
                    Entity account = service.Retrieve("account", accountId.Id, new ColumnSet("new_state"));
                    int state = (int)account.GetAttributeValue<OptionSetValue>("new_state").Value;
                    entity["new_callstate"] = new OptionSetValue(state);
    P.S. Since I'm here. Is there a way to check the entity type? I only want this to run when the to is an account. I have used if (accountId.LogicalName == "account") but that throws an error as well. Again thanks for any help, much appreciated.

    Friday, January 3, 2014 5:50 PM


All replies

  • Hi,
    "to" field is not a standard lookup but is an activityparty field (it can hold several records inside), and as the error suggest to you is an EntityCollection.
    Check this question on stackoverflow for a code example:


    My blog: www.crmanswers.net - Rockstar 365 Profile

    Friday, January 3, 2014 6:29 PM

  • EntityCollection recipients = (EntityCollection)entity.Attributes["to"];
    for (int i = 0; i < recipients.Entities.Count; i++)
    	ActivityParty ap = recipients[i].ToEntity<ActivityParty>();
            if (ap.PartyId.LogicalName == Account.EntityLogicalName)
            	// to-do


    Friday, January 3, 2014 6:35 PM
  • Thank you both, I should have known.. those darn activity party lookups cause me issues every time. I didn't even think about that. I was comparing it more to a case customerid where it could be more than one entity but not more than one lookup in the field. Thanks again. I've other plugins that work using the activity party I can reference too.
    Friday, January 3, 2014 6:47 PM