IOrganizationService.Delete Method

Applies To: Microsoft Dynamics CRM 2013, Microsoft Dynamics CRM Online

Deletes a record.

Namespace: Microsoft.Xrm.Sdk
Assembly: Microsoft.Xrm.Sdk (in Microsoft.Xrm.Sdk.dll)

Syntax

'Declaration
<FaultContractAttribute(GetType(OrganizationServiceFault))> _
<OperationContractAttribute> _
Sub Delete ( _
    entityName As String, _
    id As Guid _
)
[FaultContractAttribute(typeof(OrganizationServiceFault))] 
[OperationContractAttribute] 
void Delete (
    string entityName,
    Guid id
)

Parameters

  • entityName
    Type: String. The logical name of the entity that is specified in the entityId parameter.
  • id
    Type: Guid. The ID of the record that you want to delete.

Example

The following example shows how to use the Delete method to delete an account record (early bound). For this sample to work correctly, you must be connected to the server to get an IOrganizationService interface. You can find the complete sample in the sample code package in the folder SampleCode\CS\GeneralProgramming\EarlyBound\CRUDOperations.cs.

// Connect to the Organization service. 
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
{
    // This statement is required to enable early-bound type support.
    _serviceProxy.EnableProxyTypes();

    CreateRequiredRecords();

    // Instantiate an account object.
    // See the Entity Metadata topic in the SDK documentation to determine 
    // which attributes must be set for each entity.
    Account account = new Account { Name = "Fourth Coffee" };

    // Create an account record named Fourth Coffee.
    _accountId = _serviceProxy.Create(account);
    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

    // Retrieve the account containing several of its attributes.
    ColumnSet cols = new ColumnSet(
        new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });

    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
    Console.Write("retrieved ");

    // Retrieve version number of the account. Shows BigInt attribute usage.
    long? versionNumber = retrievedAccount.VersionNumber;

    if (versionNumber != null)
        Console.WriteLine("version # {0}, ", versionNumber);

    // Update the postal code attribute.
    retrievedAccount.Address1_PostalCode = "98052";

    // The address 2 postal code was set accidentally, so set it to null.
    retrievedAccount.Address2_PostalCode = null;

    // Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
    retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
    retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
    retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);

    // Shows use of a Money value.
    retrievedAccount.Revenue = new Money(5000000);

    // Shows use of a Boolean value.
    retrievedAccount.CreditOnHold = false;

    // Shows use of EntityReference.
    retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);

    // Shows use of Memo attribute.
    retrievedAccount.Description = "Account for Fourth Coffee.";

    // Update the account record.
    _serviceProxy.Update(retrievedAccount);
    Console.WriteLine("and updated.");                    

    DeleteRequiredRecords(promptforDelete);
}
' Connect to the Organization service. 
' The using statement assures that the service proxy will be properly disposed.
_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)
Using _serviceProxy
    ' This statement is required to enable early-bound type support.
    _serviceProxy.EnableProxyTypes()


    CreateRequiredRecords()

    ' Instantiate an account object.
    ' See the Entity Metadata topic in the SDK documentation to determine 
    ' which attributes must be set for each entity.
    Dim account_Renamed As Account = New Account With {.Name = "Fourth Coffee"}

    ' Create an account record named Fourth Coffee.
    _accountId = _serviceProxy.Create(account_Renamed)
    Console.Write("{0} {1} created, ", account_Renamed.LogicalName, account_Renamed.Name)

    ' Retrieve the account containing several of its attributes.
    Dim cols As New ColumnSet(New String() {"name", "address1_postalcode", "lastusedincampaign", "versionnumber"})

    Dim retrievedAccount As Account = CType(_serviceProxy.Retrieve("account", _accountId, cols), Account)
    Console.Write("retrieved ")

    ' Retrieve version number of the account. Shows BigInt attribute usage.
    Dim versionNumber? As Long = retrievedAccount.VersionNumber

    If versionNumber IsNot Nothing Then
        Console.WriteLine("version # {0}, ", versionNumber)
    End If

    ' Update the postal code attribute.
    retrievedAccount.Address1_PostalCode = "98052"

    ' The address 2 postal code was set accidentally, so set it to null.
    retrievedAccount.Address2_PostalCode = Nothing

    ' Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
    retrievedAccount.Address1_AddressTypeCode = New OptionSetValue(CInt(Fix(AccountAddress1_AddressTypeCode.Primary)))
    retrievedAccount.Address1_ShippingMethodCode = New OptionSetValue(CInt(Fix(AccountAddress1_ShippingMethodCode.DHL)))
    retrievedAccount.IndustryCode = New OptionSetValue(CInt(Fix(AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction)))

    ' Shows use of a Money value.
    retrievedAccount.Revenue = New Money(5000000)

    ' Shows use of a Boolean value.
    retrievedAccount.CreditOnHold = False

    ' Shows use of EntityReference.
    retrievedAccount.ParentAccountId = New EntityReference(Account.EntityLogicalName, _parentAccountId)

    ' Shows use of Memo attribute.
    retrievedAccount.Description = "Account for Fourth Coffee."

    ' Update the account record.
    _serviceProxy.Update(retrievedAccount)
    Console.WriteLine("and updated.")

    DeleteRequiredRecords(promptforDelete)
End Using

The following example shows how to use the Delete method to delete an account record (late bound). For this sample to work correctly, you must be connected to the server to get an IOrganizationService interface. You can find the complete sample in the sample code package in the folder SampleCode\CS\GeneralProgramming\LateBound\CRUDOperationsDE.cs.

// Instaniate an account object.
Entity account = new Entity("account");

// Set the required attributes. For account, only the name is required. 
// See the Entity Metadata topic in the SDK documentatio to determine 
// which attributes must be set for each entity.
account["name"] = "Fourth Coffee";

// Create an account record named Fourth Coffee.
_accountId = _service.Create(account);

Console.Write("{0} {1} created, ", account.LogicalName, account.Attributes["name"]);

// Create a column set to define which attributes should be retrieved.
ColumnSet attributes = new ColumnSet(new string[] { "name", "ownerid" });

// Retrieve the account and its name and ownerid attributes.
account = _service.Retrieve(account.LogicalName, _accountId, attributes);
Console.Write("retrieved, ");

// Update the postal code attribute.
account["address1_postalcode"] = "98052";

// The address 2 postal code was set accidentally, so set it to null.
account["address2_postalcode"] = null;

// Shows use of Money.
account["revenue"] = new Money(5000000);

// Shows use of boolean.
account["creditonhold"] = false;

// Update the account.
_service.Update(account);
Console.WriteLine("and updated.");

// Delete the account.
bool deleteRecords = true;

if (promptForDelete)
{
    Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
    String answer = Console.ReadLine();

    deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
}

if (deleteRecords)
{
    _service.Delete("account", _accountId);

    Console.WriteLine("Entity record(s) have been deleted.");
}
' Instaniate an account object.
Dim account As New Entity("account")

' Set the required attributes. For account, only the name is required. 
' See the Entity Metadata topic in the SDK documentatio to determine 
' which attributes must be set for each entity.
account("name") = "Fourth Coffee"

' Create an account record named Fourth Coffee.
_accountId = _service.Create(account)

Console.Write("{0} {1} created, ", account.LogicalName, account.Attributes("name"))

' Create a column set to define which attributes should be retrieved.
Dim attributes As New ColumnSet(New String() { "name", "ownerid" })

' Retrieve the account and its name and ownerid attributes.
account = _service.Retrieve(account.LogicalName, _accountId, attributes)
Console.Write("retrieved, ")

' Update the postal code attribute.
account("address1_postalcode") = "98052"

' The address 2 postal code was set accidentally, so set it to null.
account("address2_postalcode") = Nothing

' Shows use of Money.
account("revenue") = New Money(5000000)

' Shows use of boolean.
account("creditonhold") = False

' Update the account.
_service.Update(account)
Console.WriteLine("and updated.")

' Delete the account.
Dim deleteRecords As Boolean = True

If promptForDelete Then
            Console.WriteLine(vbLf & "Do you want these entity records deleted? (y/n) [y]: ")
    Dim answer As String = Console.ReadLine()

            deleteRecords = (answer.StartsWith("y") OrElse answer.StartsWith("Y") OrElse answer = String.Empty)
End If

If deleteRecords Then
    _service.Delete("account", _accountId)

    Console.WriteLine("Entity record(s) have been deleted.")
End If

Remarks

Message Availability

This message works regardless whether the caller is connected to the server or offline.

Not all entity types support this message offline. See Supported Entities later in this topic.

Privileges and Access Rights

To perform this action, the caller must have privileges on the entity that is specified in the entityName parameter and access rights on the record that is specified in the id parameter. For a list of the required privileges, see Delete Privileges. When a record is deleted, all child records are also deleted. The entire deletion fails if the caller does not have the delete privilege or access rights for any of these records.

Notes for Callers

This method may cascade to related records according to the cascade configuration for each entity relationship. For a description of how actions on a parent record affect related records, see Cascading behavior.

Typically, you should only delete records that you entered by mistake. For some record types, you can deactivate or close the record instead.

You can use this method to delete any record of an entity that supports the Delete message, including records from custom entities.

For more information about the exceptions that can be thrown when you call this method, see Handle Exceptions in Your Code.

Supported Entities

The following table shows the default entities that support this message. For the listed entities of this message, the Availability column shows Server if the caller must be connected to the server and shows Both if the caller can be either connected to, or disconnected from, the server.

Entity Availability

account

Both

activitymimeattachment

Both

annotation

Both

annualfiscalcalendar

Both

appointment

Both

asyncoperation

Server

attributemap

Server

bulkdeleteoperation

Server

bulkoperation

Server

businessunit

Server

businessunitnewsarticle

Both

calendar

Both

campaign

Both

campaignactivity

Both

campaignresponse

Both

columnmapping

Both

competitor

Both

connection

Both

connectionrole

Both

connectionroleobjecttypecode

Both

constraintbasedgroup

Both

contact

Both

contract

Server

contractdetail

Server

contracttemplate

Server

customeraddress

Both

customeropportunityrole

Both

customerrelationship

Both

discount

Server

discounttype

Server

duplicaterule

Server

duplicaterulecondition

Server

email

Both

equipment

Server

fax

Both

fieldpermission

Server

fieldsecurityprofile

Server

fixedmonthlyfiscalcalendar

Both

goal

Server

goalrollupquery

Server

import

Both

importentitymapping

Both

importfile

Both

importjob

Both

importmap

Both

incident

Both

incidentresolution

Both

invoice

Both

invoicedetail

Both

isvconfig

Server

kbarticle

Both

kbarticlecomment

Both

kbarticletemplate

Both

lead

Both

letter

Both

list

Server

lookupmapping

Both

mailmergetemplate

Both

metric

Server

monthlyfiscalcalendar

Both

msdyn_postalbum

Server

msdyn_postconfig

Server

msdyn_postruleconfig

Server

opportunity

Both

opportunityclose

Both

opportunityproduct

Both

orderclose

Both

ownermapping

Both

phonecall

Both

picklistmapping

Both

pluginassembly

Server

plugintype

Server

post

Server

postcomment

Server

postfollow

Server

postlike

Server

pricelevel

Both

principalobjectattributeaccess

Server

processsession

Both

product

Both

productpricelevel

Both

publisher

Server

publisheraddress

Server

quarterlyfiscalcalendar

Both

queue

Server

queueitem

Both

quote

Both

quoteclose

Both

quotedetail

Both

recurrencerule

Both

recurringappointmentmaster

Both

relationshiprole

Both

relationshiprolemap

Both

report

Server

reportcategory

Server

reportentity

Server

reportvisibility

Server

resourcespec

Both

role

Server

rollupfield

Server

salesliterature

Server

salesliteratureitem

Server

salesorder

Both

salesorderdetail

Both

savedquery

Server

savedqueryvisualization

Server

sdkmessageprocessingstep

Server

sdkmessageprocessingstepimage

Server

sdkmessageprocessingstepsecureconfig

Server

semiannualfiscalcalendar

Both

service

Server

serviceappointment

Both

serviceendpoint

Server

sharepointdocumentlocation

Server

sharepointsite

Server

site

Server

solution

Server

subject

Both

systemform

Server

task

Both

team

Server

template

Both

territory

Server

transactioncurrency

Server

transformationmapping

Both

transformationparametermapping

Both

uom

Server

uomschedule

Both

userentityinstancedata

Both

userentityuisettings

Both

userform

Server

userquery

Both

userqueryvisualization

Both

webresource

Server

workflow

Server

workflowdependency

Server

workflowlog

Server

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Platforms

Development Platforms

Windows Server 2008, Windows Server 2012, Windows 7 (All Versions), Windows 8 (All Versions)

Target Platforms

Windows Server 2008, ,Windows Server 2012, ,Windows 7 (All Versions),

Change History

See Also

Reference

IOrganizationService Interface
IOrganizationService Members
Microsoft.Xrm.Sdk Namespace
DeleteRequest
DeleteResponse
Delete

Other Resources

Handle Exceptions in Your Code
Troubleshooting and Error Handling

Send comments about this topic to Microsoft.
© 2013 Microsoft Corporation. All rights reserved.