user1746560
user1746560

Reputation: 113

Retrieving a single Guid in CRM 4.0

I'm new to CRM (version 4.0) and i'm trying to return a 'yearid' guide based on a given year (which is also stored in the entity).So far i've got:

    public static Guid GetYearID(string yearName)
    {

        ICrmService service = CrmServiceFactory.GetCrmService();

        // Create the query object.
        QueryExpression query = new QueryExpression("year");
        ColumnSet columns = new ColumnSet();
        columns.AddColumn("yearid");
        query.ColumnSet = columns;       

        FilterExpression filter = new FilterExpression();

        filter.FilterOperator = LogicalOperator.And;
        filter.AddCondition(new ConditionExpression
        {
            AttributeName = "yearName",
            Operator = ConditionOperator.Equal,
            Values = new object[] { yearName}
        });

        query.Criteria = filter;

    } 

But my questions are:


A) What code do in addition to this to actually store the Guid?
B) Is using a QueryExpression the most efficient way to do this?

Upvotes: 3

Views: 1568

Answers (1)

James Wood
James Wood

Reputation: 17562

Re: B) Going to sql maybe faster (I don't know by how much or even if), but I would have thought in 99% of situtations a QueryExpression is perfectly acceptable in terms of performance.

Re: A) Your're pretty close, I have completed the code below.

public static Guid GetYearID(string yearName) 
{
    ICrmService service = CrmServiceFactory.GetCrmService(); 

    // Create the query object. 
    QueryExpression query = new QueryExpression("year"); 

    //No need to ask for the id, it is always returned
    //ColumnSet columns = new ColumnSet(); 
    //columns.AddColumn("yearid");
    //query.ColumnSet = columns;

    FilterExpression filter = new FilterExpression(); 

    filter.FilterOperator = LogicalOperator.And; 
    filter.AddCondition(new ConditionExpression 
    { 
        AttributeName = "yearName", 
        Operator = ConditionOperator.Equal, 
        Values = new object[] { yearName} 
    }); 

    query.Criteria = filter; 

    //We have to use a retrieve multiple here
    //In theory we could get multiple results but we will assume we only ever get one
    BusinessEntityCollection years = service.RetrieveMultiple(query);

    DynamicEntity year = (DynamicEntity)years.BusinessEntities.First();

    return ((Guid)year["yearid"]);
}  

Upvotes: 2

Related Questions