Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

Hi Guys, getting this error while trying to trigger this plugin on associate of n:n relation. Plugin message "Associate" post Sync. Here for every n:n dcu record associated with Req plugin should create a new Door record with.

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

namespace new.newCreatedoor
{
    public class newCreatedoor : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            try
            {
                
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName.ToLower() != "new_req") { return; }
                var entityId = (entity != null) ? entity.Id : Guid.Empty;

                Relationship relationship = (Relationship)context.InputParameters["Relationship"];
                if (relationship.SchemaName != "new_dcu_req") { return; }

                var ccRecordType = entity.GetAttributeValue<OptionSetValue>("new_recordtype").Value;
                if (ccRecordType == 800000000 || ccRecordType == 800000001 || ccRecordType == 800000002 || ccRecordType == 800000003)
                {

                            var ec = GetdcuIds(service, entityId);
                            if (ec != null && ec.Entities.Count > 0)
                            {
                                foreach (var dcu in ec.Entities)
                                {
                                    var dcuId = dcureq.GetAttributeValue<Guid>("new_dcuid");
                                    if (dcuId != null)
                                    {
                                        var dcuEntity = Getdcu(service, dcuId);
                                        if (dcuEntity != null)
                                        {
                                            var doorEntity = new Entity("new_doors");

                                            doorEntity["new_recordtype"] = new OptionSetValue(800000000);

                                            if (dcuEntity.GetAttributeValue<string>("new_address") != null)
                                                doorEntity["new_accountphysicaladdress"] = dcuEntity.GetAttributeValue<string>("new_address").ToString();

                                            var newManager = dcuEntity.GetAttributeValue<EntityReference>("new_manager");
                                            if (newManager != null)
                                                doorEntity["new_accountmanagername"] = new EntityReference(newManager.LogicalName, newManager.Id);

                                            var newOperationManager = dcuEntity.GetAttributeValue<EntityReference>("new_operationmanager");
                                            if (newOperationManager != null)
                                                doorEntity["new_operationsmanager"] = newOperationManager.Name;
                                         

                                            doorEntity["new_dcuid"] = new EntityReference(dcuEntity.LogicalName, dcuEntity.Id);

                                            var newAccount = entity.GetAttributeValue<EntityReference>("new_account");
                                            if (newAccount != null)
                                                doorEntity["new_account"] = new EntityReference(newAccount.LogicalName, newAccount.Id);

                                            var newOpportunity = entity.GetAttributeValue<EntityReference>("new_opportunity");
                                            if (newOpportunity != null)
                                                doorEntity["new_opportunity"] = new EntityReference(newOpportunity.LogicalName, newOpportunity.Id);

                                            doorEntity["new_req"] = new EntityReference(entity.LogicalName, entity.Id);


                                            if (dcuEntity.Attributes.Contains("new_shipperreceiverdoor") && dcuEntity["new_shipperreceiverdoor"] != null)
                                                doorEntity["new_shipperreceiverdoor"] = dcuEntity["new_shipperreceiverdoor"].ToString();

                                            doorEntity["new_solicitordoor"] = "WCBH";

                                            if (dcuEntity.Attributes.Contains("new_costcenter") && dcuEntity["new_costcenter"] != null)
                                                doorEntity["new_costcenter"] = dcuEntity["new_costcenter"].ToString();
                                            
                                            service.Create(doorEntity);
                                        }
                                    }
                                }
                            }
                       
                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }


     public EntityCollection GetdcuIds(IOrganizationService service, Guid reqid)
        {
            var fetch = "<fetch>" +
                        "  <entity name='new_dcu_req' >" +
                        "    <all-attributes/>" +
                        "    <filter type='and' >" +
                        "      <condition attribute='new_reqid' operator='eq' value='" + reqid + "' />" +
                        "    </filter>" +
                        "  </entity>" +
                        "</fetch>";


            var erl = service.RetrieveMultiple(new FetchExpression(fetch));
            return erl;
        }

        public Entity Getdcu(IOrganizationService service, Guid dcuId)
        {
            var entity = service.Retrieve("new_dcu", dcuId, new ColumnSet("new_address", "new_manager", "new_subregion", "new_operationmanager", "new_city", "new_state", "new_shipperreceivercode", "new_costcenter"));
            return entity;
        }
    }
}

*This post is locked for comments

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    That worked, thank you Sara and Goutham.

      {
                   
                    EntityReference req = (EntityReference)context.InputParameters["Target"];
                    if (req.LogicalName != "new_dcu") { return; }
                    Entity relatedEntity = service.Retrieve("new_dcu", req.Id, new ColumnSet("new_address", "new_manager", "new_subregion", "new_operationmanager", "new_city", "new_state", "new_shipperreceiverdoor", "new_acctctrlocation", "new_costcenter"));
    
                    
                    var entityId = (req != null) ? req.Id : Guid.Empty;
    
                    Relationship relationship = (Relationship)context.InputParameters["Relationship"];
                    if (relationship.SchemaName != "new_dcu_req") { return; }
    
                    EntityReferenceCollection re = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
    
                    
                      
                                    foreach (EntityReference rel in re)
                                    {
                                            
                                            var doorEntity = new Entity("new_doors");
                                            Entity reqEntity = service.Retrieve("new_req", rel.Id, new ColumnSet("new_recordtype", "new_account", "new_opportunity"));
                                            var ccRecordType = reqEntity.GetAttributeValue<OptionSetValue>("new_recordtype").Value;
                                            if (ccRecordType == 800000000 || ccRecordType == 800000001 || ccRecordType == 800000002 || ccRecordType == 800000003)
                                            {
                                                 doorEntity["new_recordtype"] = new OptionSetValue(800000000);
    
                                                if (relatedEntity.GetAttributeValue<string>("new_address") != null)
                                                    doorEntity["new_accountphysicaladdress"] = relatedEntity.GetAttributeValue<string>("new_address").ToString();
    
                                                var newManager = relatedEntity.GetAttributeValue<EntityReference>("new_manager");
                                                if (newManager != null)
                                                    doorEntity["new_accountmanagername"] = new EntityReference(newManager.LogicalName, newManager.Id);
    
                                                var newOperationManager = relatedEntity.GetAttributeValue<EntityReference>("new_operationmanager");
                                                if (newOperationManager != null)
                                                doorEntity["new_operationsmanager"] = new EntityReference(newOperationManager.LogicalName, newOperationManager.Id); ;
                                               
    
                                                doorEntity["new_dcuid"] = new EntityReference(relatedEntity.LogicalName, relatedEntity.Id);
    
                                                var newAccount = reqEntity.GetAttributeValue<EntityReference>("new_account");
                                                if (newAccount != null)
                                                    doorEntity["new_account"] = new EntityReference(newAccount.LogicalName, newAccount.Id);
    
                                                var newOpportunity = reqEntity.GetAttributeValue<EntityReference>("new_opportunity");
                                                if (newOpportunity != null)
                                                    doorEntity["new_opportunity"] = new EntityReference(newOpportunity.LogicalName, newOpportunity.Id);
    
                                                doorEntity["new_req"] = new EntityReference(reqEntity.LogicalName, reqEntity.Id);
    
                                                if (relatedEntity.Attributes.Contains("new_shipperreceiverdoor") && relatedEntity["new_shipperreceiverdoor"] != null)
                                                    doorEntity["new_shipperreceiverdoor"] = relatedEntity["new_shipperreceiverdoor"].ToString();
    
                                                doorEntity["new_solicitordoor"] = "WCBH";
    
                                                if (relatedEntity.Attributes.Contains("new_costcenter") && relatedEntity["new_costcenter"] != null)
                                                    doorEntity["new_costcenter"] = relatedEntity["new_costcenter"].ToString();
                                                
                                                
                                             }
                                            service.Create(doorEntity);
                                     }
                           
                }


  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Ah, that is easy. (Sorry, I should have spotted it earlier). 

    It is this line. For Associate / Disassociate messages, the Target is not an Entity, but an EntityReference. So, change the following line 

    //Entity entity = (Entity)context.InputParameters["Target"]; //Will not work and throw an exception. 
    EntityReference entityReference = (EntityReference) context.InputParameters["Target"]; //Will work.

  • Verified answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Hi,

    When you are doing associate you must retrieve entity reference from context instead of entity. Here is sample code -

    //Get the Entity Reference as the Target

    EntityReference target = (EntityReference)context.InputParameters[“Target”];

    // Check the Message Name and the Target Entity

    if (context.MessageName == “Associate” && (target.LogicalName == “new_req” || target.LogicalName == “new_req”))

    {

    Check here for more details -

    community.dynamics.com/.../capture-associate-disassociate-events-in-plugins

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Hi Goutam, updated mhy post with complete code. Also, I tried debugging it and it quits the loop right after Entity entity = (Entity)context.InputParameters["Target"]; into catch exeception. So, couldn't say which line is causing error

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Thanks for the quick reply Sara, but it didn't work.

    I tried debugging it and it quits the loop right after Entity entity = (Entity)context.InputParameters["Target"]; into catch exeception.  

  • gdas Profile Picture
    gdas 50,085 on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    In addition where is the code of below method.

    var dcuEntity = Getdcu(service, dcuId);

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Hi Lucy, 

    Do you know which line is throwing the error? If I were to take an educated guess, it would be this line. 

    var newOperationManager = dcuEntity.GetAttributeValue<EntityReference>("new_operationmanager");
    if (newOperationManager != null)
    {
      //doorEntity["new_operationsmanager"] = newOperationManager.Name;
        doorEntity["new_operationsmanager"] = new EntityReference(newOperationManager.LogicalName, newOperationManager.Id);
    }
    
    
    Note: Code is directly typed in and not checked for compiler errors or tested. Kindly fix any typos etc., 
    Note2: Ignore this post. Just realized that you could be setting the Single Line Text field named new_operationsmanager in doorEntity with the Name of the lookup field.

    -Sara

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Unable to cast object of type 'Microsoft.Xrm.Sdk.EntityReference' to type 'Microsoft.Xrm.Sdk.Entity',

    Hi ,

    Did you tried to debug your code ? if not then please try to debug , you will get the lines which causes issue and share here full error logs .

    [View:https://dynamics365blocks.wordpress.com/2016/12/06/how-to-debug-a-plugin-in-dynamics-365-online-using-plugin-profiler/]

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,711 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,458 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans