Tuesday, June 16, 2009

Updating Retrieved Custom Entity Records

The update procedure for Dynamic Entities works well for updating custom entities. However, consider a scenario where you retrieve typecasted records of a custom entity meeting a certain criteria. If you wish to update certain information in these records, using DynamicEntity will throw a type cast error (as the service.retrieve function will return you not a DynamicEntity type but a custom entity type, since the entity for the query is specified by you). The resolution for this is to use the TargetUpdateCustomEntity class for the update.

For example, if you wish to retrieve “prospects” in the city “Redmond” and associate them with a certain “project”, you can use “TargetUpdateProspectsRequest” for the operation.


ColumnSet cols = new ColumnSet();
// Sets the ColumnSet's Properties

cols.Attributes = new string[] { "projectid" };
// Create the ConditionExpression

ConditionExpression condition = new ConditionExpression();


// Set the Condition for the Retrieval to get the Prospects in Redmond City condition.AttributeName = "prospectCity ";

condition.Operator = ConditionOperator.Equal;

condition.Values = new object[] { “Redmond”};


// Create the FilterExpression

FilterExpression filter = new FilterExpression();


// Set the Filter's Properties

filter.FilterOperator = LogicalOperator.And;

filter.Conditions = new ConditionExpression[] { condition };

// Create the QueryExpression Object

QueryExpression query = new QueryExpression();


// Set the QueryExpression Object's Properties

query.EntityName = EntityName.Prospect.ToString();

query.ColumnSet = cols;

query.Criteria = filter;

// Retrieve the records

BusinessEntityCollection prospects = service.RetrieveMultiple(query);
for (int i = 0; i < prospects.BusinessEntities.Length; i = i + 1)

{

//Prospect being the custom entity

Prospect objProspect = (Prospect) prospects.BusinessEntities[i];
Lookup objProjectID = new Lookup();

objProjectID.Value = projectIDValue ;


//set the property value to be updated

objProspect. projectid = objProjectID;


// Create the update target.

TargetUpdateProspect updateProspect = new TargetUpdateProspect();


// Set the properties of the target.

updateProspect.Prospect = objProspect;


// Create the update request object.

UpdateRequest update = new UpdateRequest();


// Set request properties.

update.Target = updateProspect;


// Execute the request.

UpdateResponse updated = (UpdateResponse)service.Execute(update);
}

No comments:

Post a Comment