Verwenden von Attributmetadaten

 

Veröffentlicht: Januar 2017

Gilt für: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

In diesem Thema wird mithilfe von Codeausschnitten aus dem Beipiel: Verwenden von Attributmetadaten veranschaulicht, wie allgemeine Aufgaben beim Verwenden von Attributen ausgeführt werden.

In diesem Thema

Erstellen von Attributen

Abrufen eines Attributs

Aktualisieren eines Attributs

Erstellen eines Suchattributs

Erstellen eines Kundesuchattributs

Aktualisieren eines Statuswerts

Erstellen einer Auswahlliste, die einen globalen Optionssatz verwendet

Einfügen eines neuen Statuswerts

Fügen Sie eine neue Option in einen lokalen Optionssatz ein.

Ändern der Reihenfolge von Optionen in einem lokalen Optionssatz

Löschen eines Attributs

Erstellen von Attributen

Sie erstellen Attribute, indem Sie einen der AttributeMetadata-Typen definieren und ihn anschließend der Meldung CreateAttributeRequest übergeben.

Das folgende Beispiel definiert die AttributeMetadata für eine Reihe von unterschiedlichen Typen von Attributen und fügt sie zu List<AttributeMetadata> hinzu. Am Ende des Codes werden die Attributdefinitionen einer Instanz der Klasse CreateAttributeRequest übergeben, und das Attribut wird mithilfe der Execute-Methode erstellt.

Im folgenden Beispiel wird angenommen, dass das aktuelle Anpassungspräfix "Neu" ist, da dies das standardmäßige Anpassungspräfix für den Organisationslösungsherausgeber ist. Sie sollten das Anpassungspräfix für den Lösungsherausgeber verwenden, das für den Lösungskontext sinnvoll ist.


// Create storage for new attributes being created
addedAttributes = new List<AttributeMetadata>();

// Create a boolean attribute
BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata
{
    // Set base properties
    SchemaName = "new_boolean",
    DisplayName = new Label("Sample Boolean", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Boolean Attribute", _languageCode),
    // Set extended properties
    OptionSet = new BooleanOptionSetMetadata(
        new OptionMetadata(new Label("True", _languageCode), 1),
        new OptionMetadata(new Label("False", _languageCode), 0)
        )
};

// Add to list
addedAttributes.Add(boolAttribute);

// Create a date time attribute
DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata
{
    // Set base properties
    SchemaName = "new_datetime",
    DisplayName = new Label("Sample DateTime", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("DateTime Attribute", _languageCode),
    // Set extended properties
    Format = DateTimeFormat.DateOnly,
    ImeMode = ImeMode.Disabled
};

// Add to list
addedAttributes.Add(dtAttribute);

// Create a decimal attribute   
DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata
{
    // Set base properties
    SchemaName = "new_decimal",
    DisplayName = new Label("Sample Decimal", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Decimal Attribute", _languageCode),
    // Set extended properties
    MaxValue = 100,
    MinValue = 0,
    Precision = 1
};

// Add to list
addedAttributes.Add(decimalAttribute);

// Create a integer attribute   
IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
{
    // Set base properties
    SchemaName = "new_integer",
    DisplayName = new Label("Sample Integer", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Integer Attribute", _languageCode),
    // Set extended properties
    Format = IntegerFormat.None,
    MaxValue = 100,
    MinValue = 0
};

// Add to list
addedAttributes.Add(integerAttribute);

// Create a memo attribute 
MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
{
    // Set base properties
    SchemaName = "new_memo",
    DisplayName = new Label("Sample Memo", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Memo Attribute", _languageCode),
    // Set extended properties
    Format = StringFormat.TextArea,
    ImeMode = ImeMode.Disabled,
    MaxLength = 500
};

// Add to list
addedAttributes.Add(memoAttribute);

// Create a money attribute 
MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
{
    // Set base properties
    SchemaName = "new_money",
    DisplayName = new Label("Money Picklist", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Money Attribue", _languageCode),
    // Set extended properties
    MaxValue = 1000.00,
    MinValue = 0.00,
    Precision = 1,
    PrecisionSource = 1,
    ImeMode = ImeMode.Disabled
};

// Add to list
addedAttributes.Add(moneyAttribute);

// Create a picklist attribute  
PicklistAttributeMetadata pickListAttribute =
    new PicklistAttributeMetadata
{
    // Set base properties
    SchemaName = "new_picklist",
    DisplayName = new Label("Sample Picklist", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("Picklist Attribute", _languageCode),
    // Set extended properties
    // Build local picklist options
    OptionSet = new OptionSetMetadata
        {
            IsGlobal = false,
            OptionSetType = OptionSetType.Picklist,
            Options = 
        {
            new OptionMetadata(
                new Label("Created", _languageCode), null),
            new OptionMetadata(
                new Label("Updated", _languageCode), null),
            new OptionMetadata(
                new Label("Deleted", _languageCode), null)
        }
        }
};

// Add to list
addedAttributes.Add(pickListAttribute);

// Create a string attribute
StringAttributeMetadata stringAttribute = new StringAttributeMetadata
{
    // Set base properties
    SchemaName = "new_string",
    DisplayName = new Label("Sample String", _languageCode),
    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
    Description = new Label("String Attribute", _languageCode),
    // Set extended properties
    MaxLength = 100
};

// Add to list
addedAttributes.Add(stringAttribute);

// NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
// Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

// NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

foreach (AttributeMetadata anAttribute in addedAttributes)
{
    // Create the request.
    CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
    {
        EntityName = Contact.EntityLogicalName,
        Attribute = anAttribute
    };

    // Execute the request.
    _serviceProxy.Execute(createAttributeRequest);

    Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
}

Abrufen eines Attributs

Dieses Beispiel veranschaulicht, wie die AttributeMetadata für ein Attribut mithilfe der RetrieveAttributeRequest abgerufen werden. In diesem Beispiel werden die Metadaten für ein benutzerdefiniertes Attribut StringAttributeMetadata, das als "new_string" bezeichnet wird, aus der in Erstellen von Attributen erstellten Kontaktentität abgerufen.

Hinweis

Da für RetrieveAsIfPublished "true" gilt, gibt diese Anforderung die aktuelle unveröffentlichte Definition dieses Attributs zurück. Sie können dies verwenden, wenn Sie einen Attribut-Editor erstellen und die unveröffentlichte Definition des Attributs abrufen möchten. Andernfalls sollten Sie RetrieveAsIfPublished nicht angeben.Weitere Informationen:Abrufen von nicht veröffentlichten Metadaten


// Create the request
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
    EntityLogicalName = Contact.EntityLogicalName,
    LogicalName = "new_string",
    RetrieveAsIfPublished = true
};

// Execute the request
RetrieveAttributeResponse attributeResponse =
    (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

Console.WriteLine("Retrieved the attribute {0}.",
    attributeResponse.AttributeMetadata.SchemaName);

Aktualisieren eines Attributs

Dieses Beispiel zeigt, wie ein Attribut aktualisiert wird. In diesem Beispiel wird die UpdateAttributeRequest verwendet, um die Eigenschaft AttributeMetadata.DisplayName eines zuvor abgerufenen benutzerdefinierten Attributs für die Contact-Entität zu ändern.


// Modify the retrieved attribute
AttributeMetadata retrievedAttributeMetadata =
    attributeResponse.AttributeMetadata;
retrievedAttributeMetadata.DisplayName =
    new Label("Update String Attribute", _languageCode);

// Update an attribute retrieved via RetrieveAttributeRequest
UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
{
    Attribute = retrievedAttributeMetadata,
    EntityName = Contact.EntityLogicalName,
    MergeLabels = false
};

// Execute the request
_serviceProxy.Execute(updateRequest);

Console.WriteLine("Updated the attribute {0}.",
    retrievedAttributeMetadata.SchemaName);

Erstellen eines Suchattributs

Ein Suchattribut wird mithilfe der CreateOneToManyRequest erstellt.

Dieser Beispielcode zeigt, wie ein Suchattribut erstellt wird. Das vollständige Beispiel finden Sie unter Beispiel: Erstellen und Aktualisieren von Entitäts-Metadaten

CreateOneToManyRequest req = new CreateOneToManyRequest()
{
    Lookup = new LookupAttributeMetadata()
    {
        Description = new Label("The referral (lead) from the bank account owner", 1033),
        DisplayName = new Label("Referral", 1033),
        LogicalName = "new_parent_leadid",
        SchemaName = "New_Parent_leadId",
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended)
    },
    OneToManyRelationship = new OneToManyRelationshipMetadata()
    {
        AssociatedMenuConfiguration = new AssociatedMenuConfiguration()
        {
            Behavior = AssociatedMenuBehavior.UseCollectionName,
            Group = AssociatedMenuGroup.Details,
            Label = new Label("Bank Accounts", 1033),
            Order = 10000
        },
        CascadeConfiguration = new CascadeConfiguration()
        {
            Assign = CascadeType.Cascade,
            Delete = CascadeType.Cascade,
            Merge = CascadeType.Cascade,
            Reparent = CascadeType.Cascade,
            Share = CascadeType.Cascade,
            Unshare = CascadeType.Cascade
        },
        ReferencedEntity = "lead",
        ReferencedAttribute = "leadid",
        ReferencingEntity = _customEntityName,
        SchemaName = "new_lead_new_bankaccount"
    }
};
_serviceProxy.Execute(req);

Erstellen eines Kundesuchattributs

Im Gegensatz zu einem Suchattribut wird ein Kundensuchattribut mit der CreateCustomerRelationshipsRequest-Meldung erstellt, die zwei Beziehungen zum Suchattribut hinzufügt: eine zur Account-Entität und die andere zur Contact-Entität. Sie können Beziehungen zu keinen anderen Entitäten als Account und Contact für ein Kundensuchattribut hinzufügen.

Hinweis

Diese Funktion wurde mit CRM Online 2016-Update 1 und CRM 2016 Service Pack 1 (lokal) eingeführt.

Dieser Beispielcode zeigt, wie ein Kundensuchattribut erstellt wird. Das vollständige Beispiel finden Sie unter Beispiel: Erstellen und Aktualisieren von Entitäts-Metadaten

CreateCustomerRelationshipsRequest createCustomerReq = new CreateCustomerRelationshipsRequest
{
    Lookup = new LookupAttributeMetadata
    {
        Description = new Label("The owner of the bank account", 1033),
        DisplayName = new Label("Account owner", 1033),
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired),
        SchemaName = "new_customerid"
    },
    OneToManyRelationships = new OneToManyRelationshipMetadata[]
    {
        new OneToManyRelationshipMetadata()
        {
            ReferencedEntity = "account",
            ReferencingEntity = _customEntityName,
            SchemaName = "new_bankaccount_customer_account",
        },
        new OneToManyRelationshipMetadata()
        {
            ReferencedEntity = "contact",
            ReferencingEntity = _customEntityName,
            SchemaName = "new_bankaccount_customer_contact",
        }
    },
};
_serviceProxy.Execute(createCustomerReq);

Erstellen einer Auswahlliste, die einen globalen Optionssatz verwendet

Dieses Beispiel zeigt, wie ein PicklistAttributeMetadata-Attribut erstellt wird, dem ein globaler Optionssatz zugeordnet ist.

Im folgenden Beispiel wird CreateAttributeRequest verwendet, um die Optionen für ein PicklistAttributeMetadata-Attribut festzulegen, das einen globalen Optionssatz mit einem Namen verwenden soll, der durch die Zeichenfolgenvariable _globalOptionSetName dargestellt wird.Weitere Informationen:Anpassen von globalen Optionssätzen


// Create a Picklist linked to the option set.
// Specify which entity will own the picklist, and create it.
CreateAttributeRequest createRequest = new CreateAttributeRequest
{
    EntityName = Contact.EntityLogicalName,
    Attribute = new PicklistAttributeMetadata
    {
        SchemaName = "sample_examplepicklist",
        LogicalName = "sample_examplepicklist",
        DisplayName = new Label("Example Picklist", _languageCode),
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

        // In order to relate the picklist to the global option set, be sure
        // to specify the two attributes below appropriately.
        // Failing to do so will lead to errors.
        OptionSet = new OptionSetMetadata
        {
            IsGlobal = true,
            Name = _globalOptionSetName
        }
    }
};

_serviceProxy.Execute(createRequest);

Einfügen eines neuen Statuswerts

Dieses Beispiel zeigt, wie eine neue Option Statusgrund für das Attribut StatusAttributeMetadata eingefügt wird.

Im folgenden Beispiel wird die InsertStatusValueRequest verwendet, um eine neue Option für das zur Entität Contact gehörende Attribut Contact.StatusCode festzulegen, das gültig ist, wenn der Contact.StateCode 0 (Aktiv) ist. Die Methode IOrganizationService.Execute verarbeitet die Anforderung.

Das folgende Beispiel erlaubt zwei gültige Optionen Statusgrund für aktive Kontakte: Aktiv und Inaktiv.


// Use InsertStatusValueRequest message to insert a new status 
// in an existing status attribute. 
// Create the request.
InsertStatusValueRequest insertStatusValueRequest =
    new InsertStatusValueRequest
{
    AttributeLogicalName = "statuscode",
    EntityLogicalName = Contact.EntityLogicalName,
    Label = new Label("Dormant", _languageCode),
    StateCode = 0
};

// Execute the request and store newly inserted value 
// for cleanup, used later part of this sample. 
_insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute(
    insertStatusValueRequest)).NewOptionValue;

Console.WriteLine("Created {0} with the value of {1}.",
    insertStatusValueRequest.Label.LocalizedLabels[0].Label,
    _insertedStatusValue);

Aktualisieren eines Statuswerts

Dieses Beispiel zeigt, wie die Beschriftung für eine Option in einem StateAttributeMetadata-Attribut geändert wird.

Im folgenden Beispiel wird UpdateStateValueRequest verwendet, um die Optionsbeschriftung Contact.StateCode von Aktiv in Öffnen zu ändern.


// Modify the state value label from Active to Open.
// Create the request.
UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
{
    AttributeLogicalName = "statecode",
    EntityLogicalName = Contact.EntityLogicalName,
    Value = 1,
    Label = new Label("Open", _languageCode)
};

// Execute the request.
_serviceProxy.Execute(updateStateValue);

Console.WriteLine(
    "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.",
    updateStateValue.AttributeLogicalName,
    updateStateValue.EntityLogicalName,
    updateStateValue.Label.LocalizedLabels[0].Label
    );

Sie können StateCode-Optionen nicht hinzufügen oder entfernen, aber Sie können die Beschriftungen der Optionen ändern.

Fügen Sie eine neue Option in einen lokalen Optionssatz ein.

Dieses Beispiel zeigt, wie Sie eine neue Option zu einem lokalen Optionssatz hinzufügen. Im folgenden Beispiel wird InsertOptionValueRequest verwendet, um eine neue Option zu einem benutzerdefinierten Attribut PicklistAttributeMetadata für die Entität Contact hinzuzufügen.


// Create a request.
InsertOptionValueRequest insertOptionValueRequest =
    new InsertOptionValueRequest
{
    AttributeLogicalName = "new_picklist",
    EntityLogicalName = Contact.EntityLogicalName,
    Label = new Label("New Picklist Label", _languageCode)
};

// Execute the request.
int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
    insertOptionValueRequest)).NewOptionValue;

Console.WriteLine("Created {0} with the value of {1}.",
    insertOptionValueRequest.Label.LocalizedLabels[0].Label,
    insertOptionValue);

Ändern der Reihenfolge von Optionen in einem lokalen Optionssatz

Dieses Beispiel zeigt, wie die Reihenfolge der Optionen in einem lokalen Optionssatz geändert wird. Das folgende Beispiel ruft ein benutzerdefiniertes PicklistAttributeMetadata-Attribut ab und ändert die Reihenfolge der ursprünglichen Optionen mithilfe der Funktion OrderByLINQ zum Sortieren von Elementen in aufsteigender Reihenfolge nach dem Beschriftungstext. Anschließend wird mithilfe von OrderOptionRequest die neue Reihenfolge der Optionen für das Attribut festgelegt.

Verwenden Sie die LINQ-Funktion OrderByDecending, um die Elemente in absteigender Reihenfolge zu sortieren.


// Use the RetrieveAttributeRequest message to retrieve  
// a attribute by it's logical name.
RetrieveAttributeRequest retrieveAttributeRequest =
    new RetrieveAttributeRequest
{
    EntityLogicalName = Contact.EntityLogicalName,
    LogicalName = "new_picklist",
    RetrieveAsIfPublished = true
};

// Execute the request.
RetrieveAttributeResponse retrieveAttributeResponse =
    (RetrieveAttributeResponse)_serviceProxy.Execute(
    retrieveAttributeRequest);

// Access the retrieved attribute.
PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
    (PicklistAttributeMetadata)
    retrieveAttributeResponse.AttributeMetadata;

// Get the current options list for the retrieved attribute.
OptionMetadata[] optionList =
    retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

// Change the order of the original option's list.
// Use the OrderBy (OrderByDescending) linq function to sort options in  
// ascending (descending) order according to label text.
// For ascending order use this:
var updateOptionList =
    optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

// For descending order use this:
// var updateOptionList =
//      optionList.OrderByDescending(
//      x => x.Label.LocalizedLabels[0].Label).ToList();

// Create the request.
OrderOptionRequest orderOptionRequest = new OrderOptionRequest
{
    // Set the properties for the request.
    AttributeLogicalName = "new_picklist",
    EntityLogicalName = Contact.EntityLogicalName,
    // Set the changed order using Select linq function 
    // to get only values in an array from the changed option list.
    Values = updateOptionList.Select(x => x.Value.Value).ToArray()
};

// Execute the request
_serviceProxy.Execute(orderOptionRequest);

Console.WriteLine("Option Set option order changed");

Löschen eines Attributs

Dieses Beispiel zeigt, wie Sie in einer List<AttributeMetadata> gespeicherte Attribute löschen, die für die Contact-Entität in Erstellen von Attributen erstellt wurden. Für jedes AttributeMetadata wird von DeleteAttributeRequest die Anforderung vorbereitet, die mithilfe von IOrganizationService.Execute verarbeitet wird.


// Delete all attributes created for this sample.
foreach (AttributeMetadata anAttribute in addedAttributes)
{
    // Create the request object
    DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest
    {
        // Set the request properties 
        EntityLogicalName = Contact.EntityLogicalName,
        LogicalName = anAttribute.SchemaName
    };
    // Execute the request
    _serviceProxy.Execute(deleteAttribute);
}

Siehe auch

Anpassen von Entitätsattributmetadaten
Meldungen für Entitätsattributsmetadaten
Beipiel: Verwenden von Attributmetadaten
Anpassen von Entitäts- und Attributzuordnungen

Microsoft Dynamics 365

© 2017 Microsoft. Alle Rechte vorbehalten. Copyright