Create table rows using the SDK for .NET

This article includes 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 primary key 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.

Dataverse stores primary key data in telemetry to help maintain the service. If you specify customized primary key values, don't use sensitive information in those values.

With elastic tables, you can create records with duplicate primary key values and different partitionid values. However, this pattern is not compatible with model-driven or canvas Power Apps. Learn about setting the primary key value with elastic tables

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);

Use the CreateRequest class

Instead of using the IOrganizationService.Create method, you can use either the late-bound Entity class or the early-bound generated entity classes with the CreateRequest by setting the entity instance to the CreateRequest.Target property and then using the IOrganizationService.Execute method to get a CreateResponse instance. The ID of the created account table row is in the CreateResponse.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.

Use the CreateMultipleRequest class

When you need to create multiple records of the same type, the CreateMultipleRequest class is the most performant way. More information: Bulk Operation messages

For standard tables, when you create a new table row, you can also create related rows in the same operation. This is called deep insert.

The following late-bound and early-bound examples 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 also create three related Task rows using the account Account_Tasks one-to-many relationship where the task regardingobjectid lookup is the ReferencingAttribute.

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);

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 SDK for .NET

Set default values from the primary table row

When people create new rows in the application, they're often 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 has 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 are 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 an entity instance with default values already set.

The following code creates a new contact that is associated with an existing account. The contact is associated with the specified account and certain attribute values, like Telephone1 and various address values shared between the account and contact are 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's 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're creating large numbers of elastic table rows that contain non-relational data, you can create the rows in storage partitions to speed up access to those rows. More information: Partitioning and horizontal scaling

See also

Retrieve a table row using the SDK for .NET
Update and delete table rows using the SDK for .NET
Associate and disassociate table rows using the SDK for .NET