Skip to main content

CRUD operations in D365 CRM using C# Plugin

 Introduction:

CRUD- Create, Reterive, Update, Delete are the operations we mainly perform and in this blog we will limit ourselves to just simple C# code to perform these actions.

The highlighted part of code is where you need to enter your data/ field/ table name.

CREATE:

Entity Recordtobecreated= new Entity("schema_name_of_entity");

Recordtobecreated["schema_name_of_field"] = "field_ value";

service.Create(Recordtobecreated);


RETRIEVE SINGLE RECORD

var cols = new ColumnSet(new String[] { "Lookup_field","Status_optionset_field" });

Entity Ouput= service.Retrieve("Target_entity_schema_name", Target_entity.Id, cols);

Once retrieved, you can get the attributes values- for lookup and option set example refer below code.

Guid LookupValue= ((EntityReference)Ouput.Attributes["Lookup_field"]).Id;

string StatusData= Ouput.FormattedValues["Status_optionset_field"];

 int Optionsetvalue= ((OptionSetValue)Ouput["Status_optionset_field"]).Value;


RETRIEVE MULTIPLE RECORD

Download fetchxml using advance find, replace double quotes with single quotes.

string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

<entity name='ENTITY NAME'>

 <attribute name='id' />

 <attribute name='name' />

  <attribute name='createdon' />

   <order attribute='name' descending='false' />

<filter type='and'>

 <condition attribute='lookup' operator='eq'  uitype='lookup_type' value='"+ id + @"' />

<condition attribute='statecode' operator='eq' value='0' />

</filter>

 </entity>

</fetch>";

 EntityCollection returnedResult = service.RetrieveMultiple(new FetchExpression(fetchXML));

Once retrieved, you can get the attributes values and count details from the returned result entity collection.


UPDATE

Entity Recordtoupdate = new Entity("schema_name_of_entity");

Recordtoupdate .Id = ID of record to be updated;

Recordtoupdate [schema_name_of_field] = field_ value";

service.Update(Recordtoupdate );


DELETE

service.Delete(schema_name_of_entity,ID of record to be deleted);


Note: Always, check for the schema name and ID provided, Use tracing service to check outputs.

Hope this helps!

Comments