Reputation: 75
I write a plugin for creating records and I'm facing following problem:
I have 2 entities. Entity1 and Entity2. Entity2 has a n-1 relationship to Entity1 and got also a lookupfield to Entity1 on it's form. In my plugin code I create an Entity1 record, and after that I want to create an Entity2 record with the lookupfield (to Entity1) filled with the just created record of Entity1. But I got an error. My code looks like this:
Entity entity1 = new Entity("new_entity1");
//Here I'm filling my entity1's fields
Guid entity1Id = service.Create(entity1);
Entity entity2 = new Entity("new_entity2");
//Here I'm filling my entity2's fields
entity2 ["new_entity1id"] = new EntityReference("new_entity1",entity1Id);
service.Create(entity2);
I'm new to CRM development so I can't really recognize the problem. I assume that maybe everything is created when the plugin code finishes, so the Entity1 record is not created by the time I create the Entity2 record, but it's just my assumption.
Any help would be great.
The error message:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxx]]: An error occured in the AccountCreateHandler plug-inDetail: <OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts"> <ErrorCode>-2147220891</ErrorCode> <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>OperationStatus</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">0</d2p1:value>
</KeyValuePairOfstringanyType> </ErrorDetails> <Message>An error occured in the AccountCreateHandler plug-in</Message> <Timestamp>2011-12-09T14:17:22.2773373Z</Timestamp> <InnerFault i:nil="true" /> <TraceText>
[Execute_Buchen: Execute_Buchen.Class1] [dc2f71e8-b216-e111-b59f-00155d0a3339: Execute_Buchen.Class1: Update of new_entity0 START:IPlugin.Execute
</TraceText> </OrganizationServiceFault>
Upvotes: 1
Views: 8007
Reputation: 3162
Try doing it this way instead.
entity2.Attributes.Add("new_entity1id",new EntityReference("new_entity1",entity1Id));
As for the exception if it's still thrown after trying the above I can only think of two things.
In the line entity2 ["new_entity1id"] = new EntityReference("new_entity1",entity1Id);
Either new_entity1id
is the wrong field name for entity2
or
That lookup field looks up to a different entity and trying to save the EntityReference
you create is throwing an Exception.
Upvotes: 2