Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Specified Cast is not valid

(0) ShareShare
ReportReport
Posted on by 165

Hello,

below is my code. I'm having a hard time figuring out when to use Guid or Entity Reference, which I think causes the error. But I might be wrong.

            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {

                Entity Order = (Entity)context.InputParameters["Target"];


                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    
                    Guid orderId = Order.Id;
                    

                    if (Order.GetAttributeValue("zst_case") != Guid.Empty) //zst_case is lookup field
                    {
                        
                        decimal inputQuantity = 1;
                        Entity orderProduct = new Entity("salesorderdetail");
                        orderProduct.Attributes.Add("salesorderid", orderId);   //salesorderis is lookup field
                        orderProduct.Attributes.Add("quantity", inputQuantity); //quantity is decimal field

                        service.Create(orderProduct);


                    }

                }

                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }

  • irenegr Profile Picture
    165 on at
    RE: Specified Cast is not valid

    Hello,

    I have successfully created a record with the code I posted above, but it only works with quantity. So, there's no error if I remove from the code these lines:

    if (product.Attributes.Contains("zst_product") && product["zst_product"]!=null))
                                    {
                                        
                                        orderProduct["productid"] = product.GetAttributeValue("zst_product");
                                    }


    Without these lines I successfully create as many records as the count number.
    When I add these lines, and after following all the debugging process as suggested before, I get the error '

    salesorder With Id = 33916f1f-c6f9-ea11-a88b-00155d006d10 Does Not Exist

    Any ideas?

  • Suggested answer
    Bipin D365 Profile Picture
    28,981 Moderator on at
    RE: Specified Cast is not valid

    Hi,

    GetAttributeValue return default value of type you specify. So I would recommend to add check condition like below before adding it into the Entity object.

    if(product.Attributes.Contains("zst_product") && product["zst_product"!=null)

    orderProduct["productid" = product.GetAttributeValue<EntityReference>("zst_product");

    if(product.Attributes.Contains(zst_quantity))

    orderProduct["quantity"=product.GetAttributeValue<decimal>("zst_quantity"));

    FYI, Sample Code to Create Sales Order Details Record from C#

    public void goCreateObject(IOrganizationService service)
    {
        Entity orderDetail = new Entity("salesorderdetail");
        Guid _soid = new Guid("660cf2c7-8c33-e711-8115-e00xxx");
        Guid _pid = new Guid("1ace6e83-8b33-e711-8115-e007yyy");
        Guid _uomid = new Guid("839e561d-17b8-4c8a-8baf-37zzz");
        bool _price = false;
        bool _product = false;
     
        orderDetail.Attributes.Add("salesorderid", new EntityReference("salesorder", _soid));
        orderDetail.Attributes.Add("productid", new EntityReference("product", _pid));
        orderDetail.Attributes.Add("quantity", Convert.ToDecimal(1));
        orderDetail.Attributes.Add("uomid", new EntityReference("uom", _uomid));
        orderDetail("ispriceoverridden") = _price;
        orderDetail("isproductoverridden") = _product;
        Guid _orderDetailId = service.Create(orderDetail);
     
    }

    Please mark my answer verified if i were helpful

  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Specified Cast is not valid

    Hello,

    I don't see the place where any null reference exception can be thrown. But from my knowledge it's not possible to create salesorderdetail instance without following fields populated:

    salesorderid - you can put Order.ToEntityReference() there

    uomid - you will have to query uom entity for details.

    Also I would recommend to change line

    orderProduct.Attributes.Add("quantity", product.GetAttributeValue<decimal>("zst_quantity"));

    to line

    orderProduct["quantity"] = product.GetAttributeValue<decimal>("zst_quantity"));

    generally speaking they do the same operation but the second one looks better from my perspective.

    Also I would highly recommend to learn on how to troubleshoot plugins using VS and plugin registration tool - www.youtube.com/watch

  • irenegr Profile Picture
    165 on at
    RE: Specified Cast is not valid

    Thank you both, again.

    Although I thought I got when to use GUID and entity reference, I made some additions to my code and now I am getting the same error again!
    Any help would be much appreciated.

     if (context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is Entity)
                {
    
                    Entity Order = (Entity)context.InputParameters["Target"];
    
    
                    IOrganizationServiceFactory serviceFactory =
                        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                    try
                    {
                        Guid caseSerialNumber = Guid.Empty;
                                         
    
                        if (Order.GetAttributeValue("zst_case") != null)
                        {
                            caseSerialNumber = Order.GetAttributeValue("zst_case").Id;
    
                            QueryExpression query = new QueryExpression("zst_parttask");
                            query.ColumnSet = new ColumnSet("zst_product", "zst_quantity"); //zst_product is lookup and zst_quantity is decimal
                            query.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, caseSerialNumber);
    
                            EntityCollection collection = service.RetrieveMultiple(query);
    
                            
    
                            if (collection.Entities.Count > 0)
                            {
                                
                                foreach(Entity product in collection.Entities)
                                {
                                    Entity orderProduct = new Entity("salesorderdetail");
                                    orderProduct["productid"] = product.GetAttributeValue("zst_product");
                                    orderProduct.Attributes.Add("quantity", product.GetAttributeValue("zst_quantity"));
                                    service.Create(orderProduct);
                                }
                                
                                
                            }
    
                                
    
    
                        }
    
                    }

  • Verified answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Specified Cast is not valid

    When you use a referential data (like lookups - EntityReference is what you should use).

    Pure Guid is mainly used when you reference PK fields (like accountid for account) and in few other rare cases (like processid/stageid fields in BPF-enabled records).

  • Verified answer
    Bipin D365 Profile Picture
    28,981 Moderator on at
    RE: Specified Cast is not valid

    Hi,

    EntityReference A Lookup attribute. A link to another record.

    Guid Usually used as the unique identifier for the entity.

    Check below link for more information.

    docs.microsoft.com/.../entity-operations

    Please mark my answer verified if i were helpful

  • irenegr Profile Picture
    165 on at
    RE: Specified Cast is not valid

    Thank you both.

    Could you explain to me when to use entity reference and when Guid?

  • Verified answer
    Bipin D365 Profile Picture
    28,981 Moderator on at
    RE: Specified Cast is not valid

    HI,

    You should also replace below line of code

    orderProduct.Attributes.Add("salesorderid", orderId);   //salesorderis is lookup field

    With 

    orderProduct["salesorderid"]=new EntityReference("salesorder", orderId);   //salesorderis is lookup field

    Please mark my answer verified if i were helpful

  • Verified answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Specified Cast is not valid

    Hello,

    Try to replace line

    if (Order.GetAttributeValue<Guid>("zst_case") != Guid.Empty) //zst_case is lookup field

    with line

    if (Order.GetAttributeValue<EntityReference>("zst_case") != null) //zst_case is lookup field

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

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Kudos to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Daivat Vartak (v-9davar) Profile Picture

Daivat Vartak (v-9d... 225 Super User 2025 Season 1

#2
Muhammad Shahzad Shafique Profile Picture

Muhammad Shahzad Sh... 106

#3
Vahid Ghafarpour Profile Picture

Vahid Ghafarpour 82 Super User 2025 Season 1

Overall leaderboard

Product updates

Dynamics 365 release plans