Thursday, June 13, 2013

Crm2011 - how to delete an entity using IOrganizationService

In order to delete the entity, you need its guid. If you do not have the Guid, you must get it first. The following code shows how to do this:

public void RemoveXrmBillHeaderByInvoiceId(string invoiceId, string org)
{
    //Get the service
    IOrganizationService xrmService = GetXrmService(org);

    //Build the Where clause using a QueryExpression
    QueryExpression query = new QueryExpression() { EntityName = "fcbt_billheader" };

    //Tell the query that I only want the guid column returned to me
    ColumnSet columnSet = new ColumnSet();       // new ColumnSet(true) -> will retreive all columns.
    columnSet.Columns.Add("fcbt_billheaderid");
    query.ColumnSet = columnSet;

    //Define the WHERE clause using a ConditionExpression
    ConditionExpression condition = new ConditionExpression() { AttributeName = "fcbt_invoiceid", Operator = ConditionOperator.Equal };
    condition.Values.Add(invoiceId);
    FilterExpression filter = new FilterExpression() { FilterOperator = LogicalOperator.And };
    filter.Conditions.Add(condition);
    query.Criteria = filter;

    EntityCollection entityCollection = xrmService.RetrieveMultiple(query);
    if (entityCollection.Entities.Count > 0)
    {
        Guid billHeaderId = entityCollection.Entities[0].GetAttributeValue<System.Guid>("fcbt_billheaderid");
        xrmService.Delete("fcbt_billheader", billHeaderId);
    }


}



No comments:

Post a Comment