Create, update, delete records in Microsoft Dynamics CE

4 min read

Summary

Below I’ve presented some basic code snippets for creating, retrieving, deleting and updating records in Dynamics 365 CE.

Create a record (late binding)

try {

//Create a New record in a custom Entity called new_customentity".
Entity newTask = new Entity("new_customentity"); {

    //Populate the 'new_name' field.
    newTask["new_name"] = "This is a record";

    //Populate the form Lookup with the current record.
    newTask["new_parent"] = new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId);

    //Call service.create method to invoke the creation of a new record.
    service.Create(newTask);

    //To avoid an execution loop, trap the depth.
     if (context.Depth <= 1) {

     service.Create(newTask);

     }
};

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Create a record (early binding)

try {

//Create a new account record using early binding.
OrganizationServiceContext context = new OrganizationServiceContext(service);

Account account = new Account() {
        FirstName = "Pamela",
        LastName = "Brown",
        Address1_Line1 = "123 Easy St.",
        Address1_City = "Atlanta",
        Address1_StateOrProvince = "GA",
        Address1_PostalCode = "32254",
        Telephone1 = "425-555-5678"
};

context.AddObject(account);
context.SaveChanges();

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Retrieve a record (service.retrieve)

try {

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) {
    entity = (Entity) context.InputParameters["Target"];
} else {
    return;
}

//Create the retrieve columnset (we only want to retrieve the attribute 'new_message').
ColumnSet attribList = new ColumnSet(new string[] {
    "new_message"
});

//Create a new Entity type and assign the service.retrieve result to new entity.
Entity myEntity = service.Retrieve(entity.LogicalName, entity.Id, attribList);

//OR Use the Organization context instead of the target.
Entity myEntity2 = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, attribList);

//Get all attributes that have any data.
Entity myEntity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(true));

//Get specific attributes.
Entity myEntity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(new string[] {"name", "telephone1"}));

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Retrieve a record using querybyattribute

try {

//Select the 'account' entity to query.
 QueryByAttribute querybyexpression = new QueryByAttribute("account");

 //Select the return columns: "name", "address1_city", "emailaddress1".
 querybyexpression.ColumnSet = new ColumnSet("name", "address1_city", "emailaddress1");

 //Select the condition column: "address1_city".
 querybyexpression.Attributes.AddRange("address1_city");

 //Add the condition: (city = "Detroit").
 querybyexpression.Values.AddRange("Detroit");

 //Pass the query into the proxy 'querybyexpression'
 EntityCollection retrieved = service.RetrieveMultiple(querybyexpression);

 //In this example, every record where 'Detroit' is the city - Create a contact record.
 //We are able to print attributes; name, address1_city & emailaddress1 because we asked for these columns to be sent back as part of the ColumnSet

 foreach(var c in retrieved.Entities) {

     Entity newContact = new Entity("contact"); 
     {
         newContact["lastname"] = c.Attributes["name"];
         newContact["address1_city"] = c.Attributes["address1_city"];
         newContact["emailaddress1"] = c.Attributes["emailaddress1"];
     };

     service.Create(newContact);
 }

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Retrieve multiple records (query expression)

try {

//Adding multiple Condition expressions in one query will always be added as AND.
 //However when you want to add operators such as AND with OR then you need to use filter expression.
 //because it can have multiple conditions inside it with operator.
 //Query using ConditionExpression and FilterExpression.

 //Create a new condition: 'condition1'.
 ConditionExpression condition1 = new ConditionExpression();

 //Define the attribute that needs to be searched: 'lastname';
 condition1.AttributeName = "new_lastname";

 //Define the Operator type: equals.
 condition1.Operator = ConditionOperator.Equal;

 //Define the value being searched: 'Brown'.
 condition1.Values.Add("Aurelio");

 //Create a New Filter & add Condition 1.
 FilterExpression filter1 = new FilterExpression();
 filter1.Conditions.Add(condition1);

 //Finally create the Query, search the entity: 'account'.
 QueryExpression query = new QueryExpression("account");

 //Define the columns that need to be retrieved.
 query.ColumnSet.AddColumns("new_firstname", "new_lastname");

 //Add the Filter to the Query.
 query.Criteria.AddFilter(filter1);

 //Add the query to the EntityCollection.
 EntityCollection result1 = service.RetrieveMultiple(query);

 foreach (var c in result1.Entities)
 {
     //Create a new Contact record.
     Entity newContact = new Entity("contact");
     {
         if (c.Attributes.Contains("new_lastname"))
         {c
             newContact["lastname"] = c.Attributes["new_lastname"];
         }
         if (c.Attributes.Contains("new_firstname"))
         {
             newContact["firstname"] = c.Attributes["new_firstname"];
         }

         service.Create(newContact);
     };
 }

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Update a record (service.update)

You must use one of the retrieve methods to return a specific record that requires the update.

try {

//Updating is similar to the Create methods string newMessage = "".

 entity["new_name"] = newMessage;

 //To avoid an execution loop, trap the depth.
 if (context.Depth <= 1) {

     service.Update(entity);
 }

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

Delete a record (service.delete)

try {

//Retrieve the lookup that will be deleted.
ColumnSet parentLookup = new ColumnSet(new string[]
                                      {
									     "new_parent"
									  });

//Initialize it to a new Entity called 'retrieved'.
Entity retrieved = service.Retrieve(entity.LogicalName, entity.Id, parentLookup);

//Once retrieved, instantiate a new Entity Reference.
EntityReference parent = (EntityReference)retrieved["new_parent"];

//Call the Service.Delete method.
service.Delete(parent.LogicalName, parent.Id);

} catch (FaultException ex) {
    throw new InvalidPluginExecutionException("An error occurred in the plug-in", ex);
}

You must be logged in to post a comment.