I am trying to update parent entity (Invoice) on create of child entity (InvoicePorduct).
on service.Update(Inv), i get the error (System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary)
Below is my code
Thanks for help :)
protected void ExecutePreInvoiceProductCreate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
// Entity entity = context.PostEntityImages["PostImage"];
if (context.MessageName == "Create")
{
try
{
Guid guidID = ((EntityReference)entity["invoiceid"]).Id;
if (!(guidID == Guid.Empty))
{
Entity inv = new Entity("invoice");
inv.Id = guidID;
using (ServiceContext svcContext = new ServiceContext(service))
{
var ts =
(from New_payments in svcContext.New_paymentSet
where
New_payments.new_invoiceid.Equals(guidID)
// group New_payments by New_payments.new_invoiceid into g
select new
{
new_Invoiceid = New_payments.new_invoiceid,
New_Amount = New_payments.New_Amount
});
foreach (var paymentAmount in ts)
{
if (paymentAmount != null)
{
paymentTotal = paymentTotal + Convert.ToDecimal(paymentAmount.New_Amount.Value);
}
else { paymentTotal = 0; }
}
var invAmount = (from i in svcContext.InvoiceSet
where
i.InvoiceId == guidID
select new
{
Invoiceid = i.InvoiceId,
TotalAmount = i.TotalAmount
});
foreach (var inc in invAmount)
{
if (inc != null)
{
totalAmount = totalAmount + Convert.ToDecimal(inc.TotalAmount.Value);
}
else { totalAmount = 0; }
}
balance = totalAmount - paymentTotal;
if (inv.Attributes.Contains("new_paymenttotal"))
{
inv.Attributes["new_paymenttotal"] = new Money(paymentTotal);
}
else
{
inv.Attributes.Add("new_paymenttotal", new Money(paymentTotal));
}
if (inv.Attributes.Contains("new_balance"))
{
inv.Attributes["new_balance"] = new Money(balance);
}
else
{
inv.Attributes.Add("new_balance", new Money(balance));
}
service.Update(inv);
}
}
}
catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the Invoice Product Create plugin:-", ex);
}
}
}}