web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

Record with Id does not exist exception CRM plugin

(0) ShareShare
ReportReport
Posted on by 87

Hi All,

I am facing an issue with my plugin code. I am trying to update discount on opportunity product when they are created. This discount is coming from the pricelist field.

After updating the discount, I am also updating the dealer revenue field on opportunity which will be calculated using est. revenue. But I am getting an exception saying, "Opportunity product with ID "  " does not exist. Below is my code. I get the exception in the highlighted line.


public void Execute(IServiceProvider serviceProvider)
{
try
{

TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
Service = ServiceFactory.CreateOrganizationService(context.UserId);

if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity && ((context.Depth <=4)))
{
Entity entity = (Entity)context.InputParameters["Target"];
Entity newEntity = new Entity("opportunityproduct");
Entity e = (Entity)context.PostEntityImages["POST_OPROD"];

Money PriceperUnit = null;
decimal quantity = 0;
decimal discount = 0;
if (entity.LogicalName != "opportunityproduct")
{
return;
}
if (context.MessageName == "Create" || context.MessageName=="Update")
{
string parentOpportunity = ((EntityReference)e.Attributes["opportunityid"]).Name;
Guid parentOppId = ((EntityReference)e.Attributes["opportunityid"]).Id;
EntityReference Oppty = ((EntityReference)e.Attributes["opportunityid"]);
var opp = new Entity("opportunity");
opp.Id = parentOppId;
quantity = (decimal)e.GetAttributeValue<decimal>("quantity");
//To retrieve the value of customer
Entity customer = myClass.GetEntity(Oppty, Service, new string[] { "customerid" });
EntityReference customerId = (EntityReference)customer.Attributes["customerid"];

//To retrive Client type of customer
String[] attributes = { "new_dealertype"};
Entity clienTypeEntity = myClass.GetEntity(customerId, Service, attributes);
OptionSetValue clientType = (OptionSetValue)(clienTypeEntity["new_dealertype"]);

//check if client type is dealer or ship to.//If yes then only we will retrieve the pricelist discount
if (!e.Attributes.Contains("new_percentagediscount"))
{

if ((clientType.Value == 100000000) || (clientType.Value == 100000001))
{
QueryExpression myQuery = new QueryExpression("opportunity");
ColumnSet columns1 = new ColumnSet("pricelevelid", "name", "customerid");
myQuery.ColumnSet = columns1;
myQuery.Criteria.AddCondition("name", ConditionOperator.Equal, parentOpportunity);
EntityCollection pricelistItems = Service.RetrieveMultiple(myQuery);
if (pricelistItems.Entities.Count > 0)
{
foreach (var a in pricelistItems.Entities)
{
if (a.Attributes.Contains("pricelevelid"))
{
var priceLst = a.GetAttributeValue<EntityReference>("pricelevelid");
QueryExpression query2 = new QueryExpression("pricelevel");
ColumnSet columns2 = new ColumnSet("new_basicdealerdiscount");

query2.ColumnSet = columns2;
query2.Criteria.AddCondition("pricelevelid", ConditionOperator.Equal, priceLst.Id);
EntityCollection discountItem = Service.RetrieveMultiple(query2);
if (discountItem.Entities.Count > 0)
{
foreach (var v in discountItem.Entities)
{
if (v.Attributes.Contains("new_basicdealerdiscount"))
{

newEntity["new_percentagediscount"] = Convert.ToDecimal(v.Attributes["new_basicdealerdiscount"]);
discount = Convert.ToDecimal(v.Attributes["new_basicdealerdiscount"]);
if (e.Attributes.Contains("priceperunit"))
{
PriceperUnit = (Money)e.GetAttributeValue<Money>("priceperunit");
myPluginOpportunityProductDiscount obj = new myPluginOpportunityProductDiscount();
newEntity["manualdiscountamount"] = obj.NewVolumeDiscountAmmount(discount, PriceperUnit, quantity);
//Fetch the updated est. revenue

String[] attributes1 = { "estimatedvalue", "opportunityid" };
Entity EstRevRef = myClass.GetEntity(Oppty, Service, attributes1);
//For dealer and ship to dealer revenue will be equal to est. revenue

Money estRev = (Money)EstRevRef["estimatedvalue"];
opp["new_dealerrevenue"] = estRev;
Service.Update(opp);
}
newEntity.Id = entity.Id;
Service.Update(newEntity);

I have tried to register my plugin as both synchronous as well as asynchronous, but the issue is same in both the cases. Please help me to correct it.

Thanks in advance !!

I have the same question (0)
  • Suggested answer
    sdfasdf Profile Picture
    842 on at

    Hi Amrita,

    It's odd that the exception is thrown on the line you highlighted:

    if (e.Attributes.Contains("priceperunit"))

    Since this line of code does not perform any operations on the server side. My recommendation would be for you to add trace calls in your plug-in to confirm where the exception is being thrown. Alternatively, you might want to debug your custom plug-in to get a little more context on what's going on.

    Within my experience, this error message would be thrown by Synchronous plug-ins registered on the Create operation of any entity, that try to call the Update operation on the record being created. Since synchronous plug-ins run in a transaction, such an Update is expected to fail.

    With your tracing strategy you might want to determine which record does not exist by logging the ID of the record being created, and comparing it with the one mentioned by the error message to see if you're experiencing the scenario I described above..

    Hope it helps.

  • Amrita P Profile Picture
    87 on at

    Hello Nathan,

    Thanks for the response.

    I tried to capture the guid of the record being created in the plug-in code. While debug I found that guid is stored in variable correctly.

    But in the exception, it is saying that record with same guid does not exist.

    I even tried to register the step as asynchronous but no luck.

  • sdfasdf Profile Picture
    842 on at

    Hello Amrita,

    Have you tried debugging the application to determine precisely what line of code throws the exception? As I mentioned, it should NOT be the one you highlight previously since that particular line is not doing any server-side operations.

    Can you try and recompile your plug-in project again, update the assembly registration and try debugging once again to confirm which line is throwing the error, please?

    Also, can you please share your full source code for this plug-in as well as how precisely it is currently registered?

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 70 Super User 2025 Season 2

#2
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 33 Most Valuable Professional

#3
Daniyal Khaleel Profile Picture

Daniyal Khaleel 32 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans