Difference between QueryByAttribute and QueryExpression

 QueryByAttribute and QueryExpression:

The QueryByAttribute class is a less complex class to use than QueryExpression when the query is very simple. It retrieves instances of a specific entity type by specifying a set of attributes and value pairs. Use it to create a query that meets a simple set of criteria, it can have multiple equal conditions that are combined using “AND”. Notice that QueryByAttribute does not support “OR”. the criteria can be defined using attribute-value pairs. The query returns only those entities meeting all the defined criteria.

QueryExpression provides an object oriented, strongly typed approach to developing queries against the Microsoft Dynamics CRM database. It provides an object oriented model and methods to help create queries. You can also use QueryExpression helper classes and methods for ease.


//  Create query using QueryByAttribute.
QueryByAttribute querybyattribute = new QueryByAttribute("account") {
   ColumnSet = new ColumnSet("name", "address1_city", "emailaddress1"),
   Attributes.AddRange("address1_city"),
   Values.AddRange("Redmond")
};

//  Query using ConditionExpression and FilterExpression
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "lastname";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add("Brown");            

FilterExpression filter1 = new FilterExpression();
filter1.Conditions.Add(condition1);

QueryExpression query = new QueryExpression("contact");
query.ColumnSet.AddColumns("firstname", "lastname");
query.Criteria.AddFilter(filter1);

EntityCollection result1 = _serviceProxy.RetrieveMultiple(query);
Console.WriteLine();
Console.WriteLine("Query using Query Expression with ConditionExpression and FilterExpression");
Console.WriteLine("---------------------------------------");

foreach (var a in result1.Entities)
{
    Console.WriteLine("Name: " + a.Attributes["firstname"] + " " + a.Attributes["lastname"]);
}
Console.WriteLine("---------------------------------------");

Cheers,
Advertisements

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s