Create table rows using the Organization Service

This topic will include examples using both late-bound and early-bound programming styles. More information:

Basic Create

The following examples show how to create a table row using the late-bound and early-bound programming style.

Each of the examples uses a svc variable that represents an instance of a class that implements the methods in the IOrganizationService interface. For information about the classes that support this interface see IOrganizationService Interface.

Note

Each table has a unique identifier column which you can specify when creating a row. In most cases you should allow the system to set this for you because the values generated by the system are optimized for best performance.

Late-bound example

The following example shows using the Entity class to create an account using the IOrganizationService.Create method.

//Use Entity class with entity logical name
var account = new Entity("account");

// set attribute values
    // string primary name
    account["name"] = "Contoso";
    // Boolean (Two option)
    account["creditonhold"] = false;
    // DateTime
    account["lastonholdtime"] = new DateTime(2017, 1, 1);
    // Double
    account["address1_latitude"] = 47.642311;
    account["address1_longitude"] = -122.136841;
    // Int
    account["numberofemployees"] = 500;
    // Money
    account["revenue"] = new Money(new decimal(5000000.00));
    // Picklist (Option set)
    account["accountcategorycode"] = new OptionSetValue(1); //Preferred customer

//Create the account
Guid accountid = svc.Create(account);

Early-bound example

The following example shows using the generated Account class to create an account using the IOrganizationService.Create method.

The Account class is derived from the Entity class

var account = new Account();
// set attribute values
    // string primary name
    account.Name = "Contoso";
    // Boolean (Two option)
    account.CreditOnHold = false;
    // DateTime
    account.LastOnHoldTime = new DateTime(2017, 1, 1);
    // Double
    account.Address1_Latitude = 47.642311;
    account.Address1_Longitude = -122.136841;
    // Int
    account.NumberOfEmployees = 500;
    // Money
    account.Revenue = new Money(new decimal(5000000.00));
    // Picklist (Option set)
    account.AccountCategoryCode = new OptionSetValue(1); //Preferred customer

//Create the account
Guid accountid = svc.Create(account);

Use the CreateRequest class

Instead of using the IOrganizationService.Create method, you can use either the late-bound Entity class or the early-bound entity classes with the CreateRequest class by setting the entity instance to the Target property and then using the IOrganizationService.Execute method to get a CreateResponse. The id of the created account table row will be in the id property value.

var request = new CreateRequest() { Target = account };
var response  = (CreateResponse)svc.Execute(request);
Guid accountid = response.id;

When to use the CreateRequest class

You must use the CreateRequest class if you want to pass optional parameters. There are two cases where you might need special parameters.

When you create a new table row you can also create related rows in the same operation.

The following late-bound and early-bound examples will create an Account and a Contact related to that account using the contact account_primary_contact one-to-many relationship where the account primarycontactid lookup is the ReferencingAttribute.

The examples will also create three related Task rows using the account Account_Tasks one-to-many relationship where the task regardingobjectid lookup is the ReferencingAttribute.

Late-bound example

In the late-bound style you must explicitly add one or more related entities (rows) to an EntityCollection and then use the Relationship class to specify the relationship using the SchemaName of the relationship before you can add them to the Entity.RelatedEntities property.

// Use Entity class with entity logical name
var account = new Entity("account");

// Set attribute values
    // string primary name
    account["name"] = "Sample Account";

// Create Primary contact
var primaryContact = new Entity("contact");
primaryContact["firstname"] = "John";
primaryContact["lastname"] = "Smith";

// Add the contact to an EntityCollection
EntityCollection primaryContactCollection = new EntityCollection();
primaryContactCollection.Entities.Add(primaryContact);

// Set the value to the relationship
account.RelatedEntities[new Relationship("account_primary_contact")] = primaryContactCollection;

// Add related tasks to create
var taskList = new List<Entity>() {
            new Entity("task") { ["subject"] = "Task 1" },
            new Entity("task") { ["subject"] = "Task 2" },
            new Entity("task") { ["subject"] = "Task 3" }
        };

// Add the tasks to an EntityCollection
EntityCollection tasks = new EntityCollection(taskList);

// Set the value to the relationship
account.RelatedEntities[new Relationship("Account_Tasks")] = tasks;

// Create the account
Guid accountid = svc.Create(account);

Early-bound example

With early-bound classes you can write less code because the classes include definitions of the relationships.

var account = new Account();
// set attribute values
    // string primary name
    account.Name = "Sample Account";

    // Set the account primary contact
    account.account_primary_contact = new Contact()
    { FirstName = "John", LastName = "Smith" };

// Set a list of Tasks to create
account.Account_Tasks = new List<Task>() {
        new Task() { Subject = "Task 1" },
        new Task() { Subject = "Task 2" },
        new Task() { Subject = "Task 3" }
    };

// Create the account
Guid accountid = svc.Create(account);

Associate table rows on create

You can associate any new row with an existing row when you create it in the same way you would when updating it. You must use an EntityReference to set the value of a lookup column (attribute).

This lookup assignment is the same for both early and late-bound styles.

//Use Entity class with entity logical name
var account = new Entity("account");

// set attribute values
    //string primary name
    account["name"] = "Sample Account";

Guid primarycontactid = new Guid("e6fa5509-2582-e811-a95e-000d3af40ae7");

account["primarycontactid"] = new EntityReference("contact", primarycontactid);

//Create the account
Guid accountid = svc.Create(account);

Use alternate keys

If you don't know the id of the table row and the following conditions are true:

  • You have configured alternate keys for the table
  • You know the key values

You can use the alternate EntityReference constructors using the keyName and keyValue parameters.

account["primarycontactid"] = new EntityReference("contact", "sample_username", "john.smith123");

Note

Alternate keys are usually used only for data integration scenarios

More information:

Check for duplicate records

More information: Detect duplicate data using the Organization service

Set default values from the primary table row

When people create new rows in the application they are usually created in the context of another row. For example, you might create a new contact row in the context of an account. When this happens certain column values from the account are copied into the contact form. This expedites the creation of the new related row because the new row will have some default values set so that the person editing the row to be created doesn't need to enter those values. They can change the values if they like before saving.

The values that will be copied over when a new row is created this way is controlled by configurations applied to the Microsoft Dataverse environment, so it can vary between environments.

More information:

As a developer, you can use the InitializeFromRequest class to generate a table row with those default values already set.

The following code will create a new contact that is associated with an existing account. The contact will be associated with the specified account and certain attribute values, like Telephone1 and various address values shared between the account and contact will be set by default.

//The account that the contact will be associated with:
var parentAccount = new EntityReference("account", new Guid("a976763a-ba1c-e811-a954-000d3af451d6"));

// Initialize a new contact entity with default values from the account.
var request = new InitializeFromRequest()
{
    EntityMoniker = parentAccount,
    TargetEntityName = "contact"

};

var response = (InitializeFromResponse)svc.Execute(request);
//Get the Entity from the response
Entity contact = response.Entity;

// Set values that are not from the account
contact["firstname"] = "Joe";
contact["lastname"] = "Smith";

// Create the contact
Guid contactid = svc.Create(contact);

Use Upsert

Another way to create a table row is by using the UpsertRequest class. An upsert will create a new row when there is no existing row that has the unique identifiers included in the row passed with the request.

More information: Use Upsert

Create documents in storage partitions

If you are creating large numbers of table rows that contain non-relational data, you can create the rows in storage partitions to speed up access to those rows. More information: Improve performance when accessing documents using storage partitions

See also

Retrieve a table row using the Organization Service
Update and delete table rows using the Organization Service
Associate and disassociate table rows using the Organization Service