This blog is an extension of my last blog
Step by step plugin tutorial using Developer's Toolkit Part 2. We used “Create Wrapper” method to generate strongly typed classes. In this blog, we will use OrganizationServiceContext to create “Task” entity instead of using service.Create() method. To use OrganizationServiceContext in the plugin, we need to add reference to Microsoft.Xrm.Sdk.Client at the top of the class.
using Microsoft.Xrm.Sdk.Client;
Now create an instance of OrganizationServiceContext by passing the OrganizationService as shown below
// TODO: Implement your custom Plug-in business logic.
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
//ITracingService tracingService = localContext.TracingService;
//create a service context
var ServiceContext = new OrganizationServiceContext(service);
Now replace the
service.Create(task);
with
ServiceContext.AddObject(task);
ServiceContext.SaveChanges();
Deploy the plugin and test it.
Advantages of using OrganizationServiceContext
The biggest advantage of using OrganizationServiceContext is that we can track multiple entities/operations and save all the changes with ServiceContext.SaveChanges(); statement. Have a look at this
article on MSDN.