다음을 통해 공유


IOrganizationService.Create 메서드

Creates a record.

네임스페이스: Microsoft.Xrm.Sdk
어셈블리: Microsoft.Xrm.Sdk(Microsoft.Xrm.Sdk.dll에 있음)

구문

‘선언
<OperationContractAttribute> _
<FaultContractAttribute(GetType(OrganizationServiceFault))> _
Function Create ( _
    entity As Entity _
) As Guid
[OperationContractAttribute] 
[FaultContractAttribute(typeof(OrganizationServiceFault))] 
Guid Create (
    Entity entity
)

매개 변수

  • entity
    Type: Entity. An entity instance that contains the properties to set in the newly created record.

반환 값

Type:Guid
The ID of the newly created record.

예제

The following example shows how to use the Create method to create an account record (early bound). For this sample to work correctly, you must be connected to the server to instantiate 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
    // 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);
}

The following example shows how to use the Create method to create an account record (late bound). For this sample to work correctly, you must be connected to the server to instantiate 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.");
}

설명

Message Availability

이 메시지는 호출자가 서버에 연결되어 있는지 아니면 오프라인인지에 관계없이 작동합니다.

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 entity parameter. For a list of the required privileges, see Create Privileges.

Notes for Callers

This method creates one record in a transaction. To create a record that has related records in a transaction, use CreateRequest.

By default the caller becomes the owner for the new record. However, for the caller to own the new record, it must have both Create and Read privileges for the entity. For more information, see Privileges by Entity. Alternatively, you can set the ownerid property to the ID of another user.

The entity instance that is specified as a parameter must contain values for all the attributes where the RequiredLevel is set to SystemRequired. You can see this in the metadata topic for the entity. If the entity instance includes properties where IsValidForCreate is false, the values are ignored. 조직의 메타데이터에서 이 정보를 찾을 수 있습니다. 앞의 메타데이터 브라우저 정보를 참조하십시오.

에 대한 자세한 내용은 the exceptions that can be thrown when this method is called, see Handle Exceptions in Your Code.

Supported Entities

You can use this method to create any record of an entity that supports the Create message, including custom entities.

다음 표에서는 이 메시지를 지원하는 기본 엔터티를 보여 줍니다. 호출자가 서버에 확실히 연결된 경우 이 메시지의 나열된 엔터티에 대한 사용 가능성 열에 서버가 표시되고 호출자가 서버에 연결되거나 서버에서 연결이 끊어진 상태일 수 있는 경우 모두가 표시됩니다.

Entity Availability

Account

2 (Both)

ActivityMimeAttachment

2 (Both)

Annotation

2 (Both)

AnnualFiscalCalendar

2 (Both)

Appointment

2 (Both)

AsyncOperation

2 (Both)

AttributeMap

2 (Both)

BusinessUnit

2 (Both)

BusinessUnitNewsArticle

2 (Both)

Calendar

2 (Both)

Campaign

2 (Both)

CampaignActivity

2 (Both)

CampaignResponse

2 (Both)

ColumnMapping

2 (Both)

Competitor

2 (Both)

Connection

2 (Both)

ConnectionRole

2 (Both)

ConnectionRoleObjectTypeCode

2 (Both)

ConstraintBasedGroup

2 (Both)

Contact

2 (Both)

Contract

2 (Both)

ContractDetail

2 (Both)

ContractTemplate

2 (Both)

ConvertRule

2 (Both)

ConvertRuleItem

2 (Both)

CustomerAddress

2 (Both)

CustomerOpportunityRole

2 (Both)

CustomerRelationship

2 (Both)

Discount

2 (Both)

DiscountType

2 (Both)

DuplicateRule

2 (Both)

DuplicateRuleCondition

2 (Both)

DynamicProperty

2 (Both)

DynamicPropertyAssociation

2 (Both)

DynamicPropertyInstance

2 (Both)

DynamicPropertyOptionSetItem

2 (Both)

Email

2 (Both)

EmailServerProfile

2 (Both)

Entitlement

2 (Both)

EntitlementChannel

2 (Both)

EntitlementTemplate

2 (Both)

EntitlementTemplateChannel

2 (Both)

Equipment

2 (Both)

ExchangeSyncIdMapping

2 (Both)

Fax

2 (Both)

FieldPermission

2 (Both)

FieldSecurityProfile

2 (Both)

FixedMonthlyFiscalCalendar

2 (Both)

Goal

2 (Both)

GoalRollupQuery

2 (Both)

HierarchyRule

2 (Both)

HierarchySecurityConfiguration

2 (Both)

Import

2 (Both)

ImportEntityMapping

2 (Both)

ImportFile

2 (Both)

ImportJob

2 (Both)

ImportMap

2 (Both)

Incident

2 (Both)

IncidentResolution

2 (Both)

Invoice

2 (Both)

InvoiceDetail

2 (Both)

IsvConfig

2 (Both)

KbArticle

2 (Both)

KbArticleComment

2 (Both)

KbArticleTemplate

2 (Both)

Lead

2 (Both)

Letter

2 (Both)

List

2 (Both)

LookUpMapping

2 (Both)

Mailbox

2 (Both)

MailMergeTemplate

2 (Both)

Metric

2 (Both)

MonthlyFiscalCalendar

2 (Both)

msdyn_PostAlbum

2 (Both)

msdyn_PostConfig

2 (Both)

msdyn_PostRuleConfig

2 (Both)

msdyn_wallsavedquery

2 (Both)

msdyn_wallsavedqueryusersettings

2 (Both)

Opportunity

2 (Both)

OpportunityClose

2 (Both)

OpportunityProduct

2 (Both)

OrderClose

2 (Both)

OrganizationUI

2 (Both)

OwnerMapping

2 (Both)

PhoneCall

2 (Both)

PickListMapping

2 (Both)

PluginAssembly

2 (Both)

PluginType

2 (Both)

Position

2 (Both)

Post

2 (Both)

PostComment

2 (Both)

PostFollow

2 (Both)

PostLike

2 (Both)

PriceLevel

2 (Both)

PrincipalObjectAttributeAccess

2 (Both)

ProcessSession

2 (Both)

ProcessTrigger

2 (Both)

Product

2 (Both)

ProductAssociation

2 (Both)

ProductPriceLevel

2 (Both)

ProductSubstitute

2 (Both)

Publisher

2 (Both)

PublisherAddress

2 (Both)

QuarterlyFiscalCalendar

2 (Both)

Queue

2 (Both)

QueueItem

2 (Both)

Quote

2 (Both)

QuoteClose

2 (Both)

QuoteDetail

2 (Both)

RecurrenceRule

2 (Both)

RecurringAppointmentMaster

2 (Both)

RelationshipRole

2 (Both)

RelationshipRoleMap

2 (Both)

Report

2 (Both)

ReportCategory

2 (Both)

ReportEntity

2 (Both)

ReportVisibility

2 (Both)

ResourceSpec

2 (Both)

Role

2 (Both)

RollupField

2 (Both)

RoutingRule

2 (Both)

RoutingRuleItem

2 (Both)

SalesLiterature

2 (Both)

SalesLiteratureItem

2 (Both)

SalesOrder

2 (Both)

SalesOrderDetail

2 (Both)

SavedQuery

2 (Both)

SavedQueryVisualization

2 (Both)

SdkMessageProcessingStep

2 (Both)

SdkMessageProcessingStepImage

2 (Both)

SdkMessageProcessingStepSecureConfig

2 (Both)

SemiAnnualFiscalCalendar

2 (Both)

Service

2 (Both)

ServiceAppointment

2 (Both)

ServiceEndpoint

2 (Both)

SharePointDocument

2 (Both)

SharePointDocumentLocation

2 (Both)

SharePointSite

2 (Both)

Site

2 (Both)

SLA

2 (Both)

SLAItem

2 (Both)

SLAKPIInstance

2 (Both)

SocialActivity

2 (Both)

SocialInsightsConfiguration

2 (Both)

SocialProfile

2 (Both)

Solution

2 (Both)

Subject

2 (Both)

SystemForm

2 (Both)

SystemUser

2 (Both)

Task

2 (Both)

Team

2 (Both)

TeamTemplate

2 (Both)

Template

2 (Both)

Territory

2 (Both)

TraceLog

2 (Both)

TransactionCurrency

2 (Both)

TransformationMapping

2 (Both)

TransformationParameterMapping

2 (Both)

UoM

2 (Both)

UoMSchedule

2 (Both)

UserEntityInstanceData

2 (Both)

UserEntityUISettings

2 (Both)

UserForm

2 (Both)

UserQuery

2 (Both)

UserQueryVisualization

2 (Both)

WebResource

2 (Both)

Workflow

2 (Both)

WorkflowDependency

2 (Both)

WorkflowLog

2 (Both)

스레드 보안

이 형식의 공용 정적(Visual Basic에서는 Shared) 구성원은 스레드로부터 안전합니다. 인스턴스 구성원은 스레드로부터 안전하지 않을 수 있습니다.

플랫폼

Development Platforms

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

Target Platforms

Windows Server 2008,Windows Server 2012,Windows 7

Change History

참고 항목

참조

IOrganizationService 인터페이스
IOrganizationService 구성원
Microsoft.Xrm.Sdk 네임스페이스
CreateRequest
CreateResponse
Create

기타 리소스

Sample: Create, Retrieve, Update and Delete (Early Bound)
Sample: Create, Retrieve, Update and Delete a Dashboard
Handle Exceptions in Your Code
Troubleshooting and Error Handling

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