Jaa


Use the OrganizationServiceContext class

 

Applies To: Dynamics CRM 2015

In Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, you can use the OrganizationServiceProxy class to access the Web services. Alternatively, you can use the OrganizationServiceContext generated by the code generation tool to gain access to additional functionality. The OrganizationServiceContext class lets you track changes, manage identities and relationships, and gives you access to the Microsoft Dynamics CRM LINQ provider. This class also contains a OrganizationServiceContext.SaveChanges method that you use to submit the changes to data that the context is tracking. This class is based on the same concept as the DataServiceContext class in Windows Communication Foundation (WCF) Data Services.

To generate this class, provide a value for the /serviceContextName parameter when you generate early bound types. The code generation tool uses this name as the name of the generated class. For more information about how to use the code generation tool, see Create early bound entity classes with the code generation tool (CrmSvcUtil.exe). You can use the organization service context when you develop applications, plug-ins, and workflow activities.

In This Topic

How to use the OrganizationServiceContext class

Track changes with the OrganizationServiceContext class

Track related objects with the OrganizationServiceContext class

Save changes with the OrganizationServiceContext class

Use virtual methods when the context is changed

How to use the OrganizationServiceContext class

To instantiate the context class, you must pass the class constructor an object that implements the IOrganizationService interface. One option is to pass an instance of the OrganizationServiceProxy class. For more information about the T:Microsoft.Xrm.Sdk.IorganizationService interface, see Use the IOrganizationService web service to read and write data or metadata.

The following code example shows how to create a new instance of the context class. In this example, the context class was named AdventureWorksCycleServiceContext by specifying the name using the /serviceContextName parameter on the code generation tool:

//For early bound types to work correctly, they have to be enabled on the proxy.
_serviceProxy.EnableProxyTypes();
AdventureWorksCycleServiceContext context = new AdventureWorksCycleServiceContext(_serviceProxy);

After you create the organization service context object, you can begin to track create, modify, or delete entities. For example, the following code example shows how to instantiate a new contact, and then save it to a Microsoft Dynamics CRM server by using the service context object.

//  Create a new contact record;
AdventureWorksCycleServiceContext context = new AdventureWorksCycleServiceContext (_serviceProxy);
Contact contact = new Contact() 
 {
   FirstName = "Pamela",
   LastName = "Brown",
   Address1_Line1 = "123 Easy St.",
   Address1_City = "Atlanta",
   Address1_StateOrProvince = "GA",
   Address1_PostalCode = "32254",
   Telephone1 = "425-555-5678"   };
context.AddObject(contact);
context.SaveChanges();

There are several points to note in the previous code example. First, after a new contact is instantiated, you pass that contact object to the OrganizationServiceContext.AddObject method so the context can begin tracking the object. The second point to note is that the new object is saved to the server by using the OrganizationServiceContext.SaveChanges method.

The organization service context must track any entity or relationship that you want to submit to Microsoft Dynamics CRM. For example, you could retrieve a record with a LINQ query and the context would track that entity or you could use the OrganizationServiceContext.Attach method to cause the context to begin tracking the entity. You can work with data in a client application and create new entities, create related entities, and modify existing entities, but you must call the SaveChanges method on tracked entities to commit changes to the Microsoft Dynamics CRM server.

Track changes with the OrganizationServiceContext class

To determine how an entity is tracked by the context, you can check the EntityState property on the entity instance. You must notify the organization service context to track an entity from Microsoft Dynamics CRM by calling various methods or by using a LINQ query. All entities returned from a .NET Language-Integrated Query (LINQ) query are tracked by the service context.

You can add objects to the service context by calling one of the following methods in OrganizationServiceContext.

Method

Use

AddObject

Adds an entity to the set of entities the organization service context is tracking. The status of the entity in the context is set to Created. If the SaveChanges method is called, this record will be created or added to the server.

Attach

Adds an entity to the set of entities the organization service context is tracking. The status of the entity in the context is set to Unchanged. If the SaveChanges method is called, this entity will not be sent to the server unless its status changes.

CreateQuery

Adds the results of a query to the set of entities the organization service context is tracking.

In CRM and CRM Online, the organization service context lets you create and update relationships between entities. The navigation properties generated by the CrmSvcUtil tool and located in the early-bound classes let you access and change related entity properties and relationships. The organization service context must be tracking the related entity for the related entity to be available to be updated on the server.

Use the following methods in OrganizationServiceContext to work with related entities and to add the entity to the service context:

Method

Use

AddRelatedObject

Adds the target to the context. Calls the Attach method on the target entity and then calls the AddLink method between the source entity and the target (related) entity.

AttachLink

Adds the related entity to the context for tracking. The status of the entity in the context is set to Unchanged.

AddLink

Creates a relationship between the source and target entities. Adds the target to the context. The status of the target entity in the context is set to Created.

LoadProperty

Loads the related entity set for the specified relationship. Gives access to related entities by using the navigation property. Call the AddObject method on the related entity after you have accessed the entity by using a navigation property on the parent entity.

UpdateObject

Changes the state of the specified entity in the OrganizationServiceContext to Modified.

DeleteObject

Changes the state of the specified entity to be deleted in the OrganizationServiceContext.

Related entities for entities you have retrieved using LINQ will be null until you use LoadProperty to retrieve them. The following code sample shows how to access Task records associated with a specific Contact record.

Contact pam = context.ContactSet.Where(c => c.FirstName == "Pamela").FirstOrDefault();
if (pam != null)
{
// pam.Contact_Tasks is null until you use LoadProperty
    context.LoadProperty(pam, "Contact_Tasks");
    Task firstTask = pam.Contact_Tasks.FirstOrDefault();
}

Save changes with the OrganizationServiceContext class

The organization service context holds a graph of the entities it is tracking. The order in which the organization service context processes entity changes and submits them to the server is important. Updates to primary entity are processed, and then related entities are processed. If a value is set on the primary entity by the related entity, that value is used when updating data on the server.

If an error occurs when entity information is being saved, a new exception type that contains the SaveChangesResult is thrown by the OrganizationServiceContext.SaveChanges method, regardless of the value of the SaveChangesOptions parameter that is passed into the method.

Use virtual methods when the context is changed

Sometimes it may be necessary to take actions based on changes in the OrganizationServiceContext. To facilitate this, virtual methods are provided to allow you to intercept or be notified of an operation. To take advantage of these methods, you either have to derive from OrganizationServiceContext or change the generated organization service context.The following table lists the virtual methods.

Method

Description

OnBeginEntityTracking

Called after an entity is attached to the OrganizationServiceContext.

OnBeginLinkTracking

Called after a link is attached to the OrganizationServiceContext.

OnEndEntityTracking

Called after an entity is detached from the OrganizationServiceContext.

OnEndLinkTracking

Called after a link is detached from the OrganizationServiceContext.

OnExecuting

Called immediately before a request is submitted to the Microsoft Dynamics CRM Server.

OnExecute

Called immediately after a request is submitted to the Microsoft Dynamics CRM Server, regardless of whether an exception occurred or not.

OnSavingChanges

Called before any operations occur after a call to SaveChanges.

OnSaveChanges

Called when all of the operations for a call to SaveChanges have completed, or when there is a failure.

See Also

T:Microsoft.Xrm.Sdk.IorganizationService
OrganizationServiceContext
Use the early bound entity classes in code
Sample: Complex LINQ queries
Create early bound entity classes with the code generation tool (CrmSvcUtil.exe)
Use the early-bound entity classes for create, update, and delete

© 2016 Microsoft. All rights reserved. Copyright