Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving list of Entities

In CRM 2011 I can do the usual Create, Update, Delete operations using EarlyBoundEntities. I cant, however, seem to find an example of retrieving a list of entities using the same type of code. Is there a way of retrieving a list of items of type using EarlyBoundEntities?

I've looked through MSDN and all I can find is how to retrieve an Entity if I know its GUID already.

 // Retrieve the account containing several of its attributes.
 ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

 Account retrievedAccount = (Account)_service.Retrieve("account", _accountId, cols);
 Console.Write("retrieved, ");

How would I for example get a list of all accounts which didnt have a phone number?

like image 546
Mauro Avatar asked Oct 14 '25 03:10

Mauro


1 Answers

If you've generated your early-bound proxy classes with the servicecontextname parameters, then you could LINQ for querying.

var context = new XrmServiceContext(service);
var accounts = context.AccountSet.Where(item => item.Telephone1 == null);

Otherwise, if you still wanted to use other query methods such as QueryExpression you could use LINQ to cast all instances to the desire early-bound type.

var contacts = service.RetrieveMultiple(new QueryExpression
                                            {
                                                EntityName = "contact",
                                                ColumnSet = new ColumnSet("firstname")
                                            })
    .Entities
    .Select(item => item.ToEntity<Contact>());

You could also use an extension method if you'd prefer:

public static IEnumerable<T> RetrieveMultiple<T>(this IOrganizationService service, QueryBase query) where T : Entity
{
    return service.RetrieveMultiple(query)
        .Entities
        .Select(item => item.ToEntity<T>());
}

Usage:

var contacts = service.RetrieveMultiple<Contact>(new QueryExpression
                                                        {
                                                            EntityName = "contact",
                                                            ColumnSet = new ColumnSet("firstname")
                                                        });
like image 88
Luke Baulch Avatar answered Oct 16 '25 18:10

Luke Baulch