-
Run fetch XML query
C#
Execute a FetchXML Query in C# for Data.
Uses a FetchXML query to retrieve records filtered by a specific attribute, enabling precise and efficient data retrieval. The query is dynamically constructed to apply filters and order the results.
// Run Fetch XML query in C#
string StrJob = "Engineer";
// Construct the FetchXML query
string fetchXML = String.Format(@"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='systemuser'>
<attribute name='fullname' />
<attribute name='systemuserid' />
<order attribute='fullname' descending='false' />
<filter type='and'>
<condition attribute='jobtitle' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>", StrJob.ToUpper());
// Execute the query
EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXML));
// Check if any results are found
if (result.Entities.Any())
{
// Assign the first result as the owner
Entity agent = result.Entities.First();
// Loop through results and log the fullname of each user
foreach (var user in result.Entities)
{
string fullName = user.GetAttributeValue<string>("fullname");
Console.WriteLine($"User Full Name: {fullName}");
}
}
else
{
Console.WriteLine("No users found with the specified job title.");
}