Retrieve Record using Alternate Keys

Instead of retrieve a single record using

Entity IOrganizationService.Retrieve(string entityName, Guid id, ColumnSet columnSet);

You can easily retrieve the record using its alternate keys if you don’t have the id in advance:

var keys = new KeyAttributeCollection
{
	{ "new_parent", parentRef.Id },
	{ "new_code", "code01" }
};

var request = new RetrieveRequest
{
	ColumnSet = new ColumnSet("field_logical_name"),
	Target = new EntityReference("entity_logical_name", keys)
};

try
{
	var response = (RetrieveResponse)service.Execute(request);
	if (response.Entity != null)
	{
		service.Delete(response.Entity.LogicalName, response.Entity.Id);
	}
}
catch (Exception)
{	
}

Note that if there is no record matched the keys, an exception will be thrown, you’ll need to handle the exception in that case.

Advertisements

Author: Khoa Nguyen

I'm a senior software engineer. I've been focusing on MS Dynamics CRM since CRM 2013. My passion is continuously study and deepen my skills in Microsoft Dynamics CRM and system integrations in order to develop highly scalable, robust and easy to maintain CRM solutions.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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