Milos Nikolic Milos Nikolic - 21 days ago 13
C# Question

Update created record in Custom Workflow Activity -CRM -C#

I have created new entity.

From that entity i call Custom Workflow Activity entity that creates opportunity.
It works, but additionally I have to change some fields on created opportunity.
(I have to add opportunity products, and have to change price list for each opportunity).

As a test I tried to Update account field after creation, but it failed field. When i populate this account field before creation, it works, so it is not about that.
Here is the part of the code:

Entity entity = null;
if (context.InputParameters != null && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
entity = (Entity)context.InputParameters["Target"];
entity = service.Retrieve(context.PrimaryEntityName, ((Guid)context.PrimaryEntityId), new ColumnSet(true));
Entity opportunity = new Entity("opportunity");
string name = entity.GetAttributeValue<string>("subject");
opportunity["name"] = name;
opportunityId = service.Create(opportunity);
EntityReference accountlookup = (EntityReference)entity.Attributes["ad_sendto"];
Guid accountId = accountlookup.Id;

opportunity["parentaccountid"] = new EntityReference("account", accountId);

To repeat, it creates opportunity, but it doesn't work for update, is there any other way to do this, or do I have some errors here?


It fails because you are trying to update opportunity entity which does not have a primary key (opportunityid) set.

Instead of updating the opportunity after it was created, why not just assign the parentaccountid during the create operation?

var opportunity = new Entity("opportunity");
opportunity["name"] = entity.GetAttributeValue<string>("subject"); ;
opportunity["parentaccountid"] = entity.Attributes["ad_sendto"];
opportunityId = service.Create(opportunity);

For future references, if you ever have to update an entity that was just created or any entity for that matter:

var opportunityToUpdate = new Entity("opportunity")
    Id = opportunityId
opportunityToUpdate["parentaccountid"] = entity.Attributes["ad_sendto"];