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.