Using Deep Insert (creating multiple new records in the same operation) in Silverlight (CRM 2011)


Sharing a basic example using which we can create Parent entity and the related entity records in the same operation\

Check out this helpful post

public MainPage()

GGContext context;

private void UserControl_Loaded(object sender, RoutedEventArgs e)
 var orgServiceUrl = "http://servername/orgname/XRMServices/2011/OrganizationData.svc";

 // initialize the context
 context = new GGContext(new Uri(orgServiceUrl));

// using client http stack
 context.HttpStack = System.Data.Services.Client.HttpStack.ClientHttp;
 context.UseDefaultCredentials = false;
 context.Credentials = new NetworkCredential("administrator", "password", "domain");
 // create contact record
 Contact contact = new Contact();
 contact.LastName = "Rana";
 contact.FirstName = "Nisha";

 // create two tasks and one email activity
 var myTask1 = new Task();
 myTask1.Subject = "Task1 created at " + DateTime.Now.ToLongTimeString();
 var myTask2 = new Task();
 myTask2.Subject = "Task2 created at " + DateTime.Now.ToLongTimeString();
 var myEmail = new Email();
 myEmail.Subject = "Email created at " + DateTime.Now.ToLongTimeString();

// add the tasks and email to their respective set

// add contact to be created to the contact set

// add the related records

 // add the link
 context.AddLink(contact, "Contact_Tasks", myTask1);
 context.AddLink(contact, "Contact_Tasks", myTask2);
 context.AddLink(contact, "Contact_Emails", myEmail);

context.BeginSaveChanges(CreateContactHandler, contact);
 private void CreateContactHandler(IAsyncResult result)
 // in the call back method call the EndSaveChanges method
 // it returns DataServiceResponse object.
 // we can get the error information from this object in case an operation fails
 // id of the created contact record
 Guid createdContactGuid = ((Contact)result.AsyncState).ContactId;

Hope it helps

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “Using Deep Insert (creating multiple new records in the same operation) in Silverlight (CRM 2011)”

  1. I tried this method when trying to create a new quote from an existing quote. Basically a quote copy process and I get an error “the context is already tracking the entity”. can you help?


Please share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.