Элементы Annotation (CSDL)

Элементы annotation в языке CSDL представляют собой настраиваемые элементы XML в концептуальной модели. Элементы annotation должны не только иметь допустимую структуру XML, но и соответствовать следующим требованиям:

  • Элементы annotation не должны находиться в каком-либо пространстве имен XML, которое зарезервировано для языка CSDL.

  • У данного элемента языка CSDL может быть больше одного дочернего элемента annotation.

  • Полные имена любых двух элементов annotation не должны совпадать.

  • Элементы annotation должны находиться после всех остальных дочерних элементов в данном элементе CSDL.

Элементы annotation могут использоваться для предоставления дополнительных метаданных об элементах в концептуальной модели. Начиная с .NET Framework версии 4 доступ к метаданным, содержащимся в элементах annotation, производится во время выполнения с помощью классов в пространстве имен System.Data.Metadata.Edm.

Пример

В следующем примере показан элемент EntityType с элементом annotation (CustomElement). В следующем примере показано применение атрибута annotation к элементам типа сущности. Дополнительные сведения см. в разделе Атрибуты annotation (язык CSDL).

<Schema Namespace="SchoolModel" Alias="Self"
        xmlns:annotation="https://schemas.microsoft.com/ado/2009/02/edm/annotation"
        xmlns="https://schemas.microsoft.com/ado/2008/09/edm">
  <EntityContainer Name="SchoolEntities" annotation:LazyLoadingEnabled="true">
    <EntitySet Name="People" EntityType="SchoolModel.Person" />
  </EntityContainer>
  <EntityType Name="Person" xmlns:p="http://CustomNamespace.com"
              p:CustomAttribute="Data here.">
    <Key>
      <PropertyRef Name="PersonID" />
    </Key>
    <Property Name="PersonID" Type="Int32" Nullable="false"
              annotation:StoreGeneratedPattern="Identity" />
    <Property Name="LastName" Type="String" Nullable="false"
              MaxLength="50" Unicode="true" FixedLength="false" />
    <Property Name="FirstName" Type="String" Nullable="false"
              MaxLength="50" Unicode="true" FixedLength="false" />
    <Property Name="HireDate" Type="DateTime" />
    <Property Name="EnrollmentDate" Type="DateTime" />
    <p:CustomElement>
      Custom metadata.
    </p:CustomElement>
  </EntityType>
</Schema>

Следующий код извлекает метаданные из элемента annotation и выводит их на консоль.

Dim collection As New EdmItemCollection("School.csdl")
Dim workspace As New MetadataWorkspace()
workspace.RegisterItemCollection(collection)
Dim contentType As EdmType
workspace.TryGetType("Person", "SchoolModel", DataSpace.CSpace, contentType)
If contentType.MetadataProperties.Contains("http://CustomNamespace.com:CustomElement") Then
    Dim annotationProperty As MetadataProperty = _
        contentType.MetadataProperties("http://CustomNamespace.com:CustomElement")
    Dim annotationValue As Object = annotationProperty.Value
    Console.WriteLine(annotationValue.ToString())
End If
EdmItemCollection collection = new EdmItemCollection("School.csdl");
MetadataWorkspace workspace = new MetadataWorkspace();
workspace.RegisterItemCollection(collection);
EdmType contentType;
workspace.TryGetType("Person", "SchoolModel", DataSpace.CSpace, out contentType);
if (contentType.MetadataProperties.Contains("http://CustomNamespace.com:CustomElement"))
{
    MetadataProperty annotationProperty =
        contentType.MetadataProperties["http://CustomNamespace.com:CustomElement"];
    object annotationValue = annotationProperty.Value;
    Console.WriteLine(annotationValue.ToString());
}

Вышеприведенный код предполагает, что файл School.csdl находится в выходном каталоге проекта, а в проект добавлены инструкции Imports и Using.

Imports System.Data.Metadata.Edm
using System.Data.Metadata.Edm;

См. также

Основные понятия

Атрибуты annotation (язык CSDL)
Спецификация языка CSDL

Другие ресурсы

Спецификации языка CSDL, SSDL и MSL