Search code examples
c#metadatadynamics-crm-2011

How to check if a field is defined?


In this blog, it's shown how to retrieve the metadata of a field.

I'd like to know how to check (other than the above combined with a try-catch-statement) whether a field exist or not.

The reason for that is that when I execute my QueryExpression, I need to know what columns to include in the ColumnSet.

The Q&D code right now is this.

private bool DoesFieldExist(String entityName, String fieldName)
{
  try
  {
    RetrieveAttributeRequest req = new RetrieveAttributeRequest();
    req.EntityLogicalName = entityName;
    req.LogicalName = fieldName;
    RetrieveAttributeResponse resp = (RetrieveAttributeResponse)service.Execute(req);
  }
  catch (Exception) { return false; }
  return true;
}

Solution

  • private bool DoesFieldExist(String entityName, String fieldName)
    {
      RetrieveEntityRequest request = new RetrieveEntityRequest
      {
        EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
        LogicalName = entityName
      };
      RetrieveEntityResponse response 
        = (RetrieveEntityResponse)service.Execute(request);
      return response.EntityMetadata.Attributes.FirstOrDefault(element 
        => element.LogicalName == fieldName) != null;
    }
    
    1. The EntityFilters requires that you add using Microsoft.Xrm.Sdk.Metadata; in order to work properly if you dislike the explicit reference in my example (and you should dislike it because it's ugly).

    2. I'd prefer to use FirstOrDefault instead of SingleOrDefault. While in this case it can't give you any problems (the attribute either is there or not), in other cases you may get an exception if there are multiple elements satisfying the condition (should you look for a match over multiple attributes or do something else that can cause that).