Wednesday, January 23, 2013

Adding multiple records to CRM2011 using Linq provider

LINQ stands to Language Integrated Query. It provides a consistent interface for querying early bound or late bound queries, all using  standard CLR types.

Review Using early binding (typed WCF classes) in CRM 2011 to review the use of the crmsvcutil.exe code -generator. Note that you have to use the  /serviceContextName:CrmDataContext switch to generate the Service Context, which is the gateway to the Linq provider.

The generated context, in this case CrmDataContext has public queryable entitysets that can be queried.
The following example shows adding multiple records to Account, with one call to CRM:

Note that even though in code only ONE call is made, multiple calls are made to the CRM service for this but it is still more efficient by about 60%.
NOTE: YOU HAVE TO USE THE .NET FRAMEWORK 4 AS THE TARGET FRAMEWORK, AND NOT THE .NET FRAMEWORK 4 CLIENT PROFILE

private void buttonExecuteLinqQuery_Click(object sender, EventArgs e)
{
    //SET UP CREDENTIALS
    Uri OrganizationUri = new Uri(textBoxServerUrl.Text + "/" + textBoxOrg.Text + "/XRMServices/2011/Organization.svc");
    ClientCredentials Credentials = new ClientCredentials();
    Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(textBoxName.Text, textBoxPassword.Text, textBoxDomain.Text);

    //INITIALIZE PIPELINE SERVICE
    OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null);
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    IOrganizationService service = (IOrganizationService)serviceProxy;

    fcbt.crm.baseline.CrmDataContext context = new fcbt.crm.baseline.CrmDataContext(service);
    context.AddObject(new fcbt.crm.baseline.Account { Name = "joe" });
    context.AddObject(new fcbt.crm.baseline.Account{Name = "pete"});
    context.AddObject(new fcbt.crm.baseline.Account{Name = "mike"});
    context.AddObject(new fcbt.crm.baseline.Account{Name = "harry"});
    context.SaveChanges();
}

No comments:

Post a Comment