关系(元数据)

实体数据模型 (EDM) 中的关系定义两个实体相关的方式。实体数据模型关系主题详细介绍有关 EDM 中的关系的信息。

ADO.NET 元数据提供 AssociationType 来表示各个 EntityType 之间的关系。AssociationType 派生自 RelationshipType 并表示一种 EDM 关联。同样,AssociationSet 描述参与特定 EDM 关联的 EntitySet。有关实体集和关联集的更多信息,请参见实体集 (EDM)关联集 (EDM)

以下代码示例演示如何通过连接获得元数据工作区,然后使用该元数据工作区以在指定模型中检索有关关系的信息。请注意,元数据工作区是一个为检索元数据提供支持的运行时服务组件。

该代码示例使用 CSpace 指定模型。CSpace 表示概念性模型的默认名称。

此代码示例包含三个方法:GetAssociationsGetAssociationSetsGetOneAssociationSet

GetAssociations 方法获取关联集合,然后循环访问此集合以访问其关联 End 成员。

GetAssociationSets 方法获得实体容器的集合,然后循环访问此集合以获取指定容器中的每个关联集。在 EDM 中,EntityContainer 表示实体集和关联集的逻辑分组。有关如何在 EDM 中定义实体容器的更多信息,请参见实体容器 (EDM)

GetOneAssociationSet 方法获得实体容器的集合,然后循环访问此集合以仅获取使用指定名称的一个关联集。

以下代码示例使用在 AdventureWorks 完整模型 (EDM) 中提供的 Adventureworks 模型。有关应用程序配置文件的示例,请参见使用 AdventureWorks 对象模型 (EDM)

using System;
using System.Data;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Collections.ObjectModel;

class GetRelationshipsExample
{
  static void Main()
  {
    try
    {
      // Establish a connection to the underlying data provider by 
      // using the connection string specified in the config file.
      using (EntityConnection connection = 
               new EntityConnection("Name=AdventureWorksEntities"))
      {
         // Open the connection.
         connection.Open();

         // Access the metadata workspace.
         MetadataWorkspace workspace = 
             connection.GetMetadataWorkspace();

         // Get associations from the conceptual model.
         GetAssociations(workspace, DataSpace.CSpace);

         // Get association sets from the conceptual model.
         GetAssociationSets(workspace, DataSpace.CSpace);

         // Get one assoiation set by using the specified 
         // relationship name from the conceptual model.
         string relationshipName = "FK_Employee_Contact_ContactID";
         GetOneAssociationSet(
           workspace, relationshipName, DataSpace.CSpace);
       }
     }
     catch (MetadataException exceptionMetadata)
     {
        Console.WriteLine("MetadataException: {0}", 
                          exceptionMetadata.Message);
     }
     catch (System.Data.MappingException exceptionMapping)
     {
        Console.WriteLine("MappingException: {0}",
                          exceptionMapping.Message);
     }
  }

  public static void GetAssociations(
   MetadataWorkspace workspace, DataSpace model)
  {
     Console.WriteLine("***Get Associations =>");
     // Get a collection of association types.
     ReadOnlyCollection<AssociationType> associationTypes = 
          workspace.GetItems<AssociationType>(model);

     // Iterate through the collection to get each association type.
     foreach (AssociationType associationType in associationTypes)
     {
        Console.WriteLine("AssociationType Name: {0}, Namespace: {1}",
                     associationType.Name,
                     associationType.NamespaceName);

        // Iterate through the collection to get 
        // each association end member.
        foreach (AssociationEndMember end in 
                        associationType.AssociationEndMembers)
        {
           Console.WriteLine(
                   "\t End Name: {0}, Type: {1}, Multiplicity: {2}",
                   end.Name,
                   end.TypeUsage.EdmType.Name,
                   end.RelationshipMultiplicity);
        }
     }
  }

  public static void GetAssociationSets(
   MetadataWorkspace workspace, DataSpace model)
  {
     Console.WriteLine("***Get Association Sets =>");
     // Get a collection of entity containers.
     ReadOnlyCollection<EntityContainer> containers = 
           workspace.GetItems<EntityContainer>(model);

     // Iterate through the collection to get each entity container.
     foreach (EntityContainer container in containers)
     {
        // Iterate through the collection to get each entity set base.
        foreach (EntitySetBase baseSet in container.BaseEntitySets)
        {
                // EntitySetBase is a super type for 
                // AssociationSet and EntitySet. 
                // Check if the current object is an instance of the 
                // AssociationSet.
                if (baseSet is AssociationSet)
                {
                    Console.WriteLine(
                     "AssociationSet Name: {0} , " +
                     "AssociationType Name: {1} ",
                     baseSet.Name, baseSet.ElementType.FullName);

                    AssociationSet associationSet = 
                                baseSet as AssociationSet;

                    // Iterate through the collection to get 
                    // each association end.
                    foreach (AssociationSetEnd end in 
                             associationSet.AssociationSetEnds)
                    {
                        Console.WriteLine(
                          "EntitySet Name: {0} , Name: {1}, " + 
                          "AssociationEndMember: {2} ",
                          end.EntitySet, 
                          end.Name, 
                          end.CorrespondingAssociationEndMember);
                    }
                }
        }
     }
  }

  public static void GetOneAssociationSet(
      MetadataWorkspace workspace, string relationshipName, 
      DataSpace model)
  {
     Console.WriteLine("***Get One AssociationSet =>");
     // Get a collection of entity containers.
     ReadOnlyCollection<EntityContainer> containers = 
            workspace.GetItems<EntityContainer>(model);

     // Iterate through the collection to get each entity container.
     foreach (EntityContainer container in containers)
     {
        RelationshipSet relationshipSet;

        // Check if the relationship with the specified name exists 
        // or not.
        if (container.TryGetRelationshipSetByName(
                      relationshipName, true, out relationshipSet))
        {
                AssociationSet associationSet = 
                                 relationshipSet as AssociationSet;
                Console.WriteLine(
                    "AssociationSet Name: {0} , " +
                    "AssociationType Name: {1} ", 
                     associationSet.Name, 
                     associationSet.ElementType.FullName);                
         }
     }
  }
}
Imports System
Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Data.EntityClient
Imports System.Data.Metadata.Edm

Class GetRelationshipsExample

  Shared Sub Main()
    Try
      ' Establish a connection to the underlying data provider by 
      ' using the connection string specified in the config file.
      Using connection As EntityConnection = _
            New EntityConnection("Name=AdventureWorksEntities")
        ' Open the conection.
         connection.Open()

        ' Access the metadata workspace.
        Dim workspace As MetadataWorkspace = _
           connection.GetMetadataWorkspace

        ' Get associations from the conceptual model.
        GetAssociations(workspace, DataSpace.CSpace)

        ' Get association sets from the conceptual model.
        GetAssociationSets(workspace, DataSpace.CSpace)

        ' Get one assoiation set by using the specified 
        ' relationship name from the conceptual model.
        Dim relationshipName As String = _
          "FK_Employee_Contact_ContactID"
        GetOneAssociationSet( _
             workspace, relationshipName, DataSpace.CSpace)
      End Using
    Catch exceptionMetadata As MetadataException
       Console.WriteLine("MetadataException: {0}", _
          exceptionMetadata.Message)
    Catch exceptionMapping As MappingException
       Console.WriteLine("MappingException: {0}", _
          exceptionMapping.Message)
    End Try
  End Sub

  Public Shared Sub GetAssociations( _
    ByVal workspace As MetadataWorkspace, ByVal model As DataSpace)

    Console.WriteLine("***Get Associations =>")

    ' Get a collection of association types.
    Dim associationTypes As ReadOnlyCollection(Of AssociationType) = _
           workspace.GetItems(Of AssociationType)(model)

    ' Iterate through the collection to get each association type.
    Dim associationType As AssociationType
    For Each associationType In associationTypes
      Console.WriteLine("AssociationType Name: {0}, Namespace: {1}", _
          associationType.Name, associationType.NamespaceName)

      ' Iterate through the collection to get 
      ' each association end member.
      Dim endMember As AssociationEndMember
      For Each endMember In associationType.AssociationEndMembers
       Console.WriteLine(ControlChars.Tab & _
         " End Name: {0}, Type: {1}, Multiplicity: {2}", _
         endMember.Name, endMember.TypeUsage.EdmType.Name, _
         endMember.RelationshipMultiplicity)
      Next
    Next
  End Sub

  Public Shared Sub GetAssociationSets( _
    ByVal workspace As MetadataWorkspace, ByVal model As DataSpace)

    Console.WriteLine("***Get Association Sets =>")
    ' Get a collection of entity containers.
    Dim containers As ReadOnlyCollection(Of EntityContainer) = _
          workspace.GetItems(Of EntityContainer)(model)
    Dim container As EntityContainer

    ' Iterate through the collection to get each entity container.
    For Each container In containers
       Dim baseSet As EntitySetBase
       ' Iterate through the collection to get each entity set base.
       For Each baseSet In container.BaseEntitySets
         ' EntitySetBase is a super type for 
         ' AssociationSet and EntitySet. 
         ' Check if the current object is an instance of the 
         ' AssociationSet.
         If TypeOf baseSet Is AssociationSet Then
            Console.WriteLine( _
             "AssociationSet Name: {0} , AssociationType Name: {1} ", _
             baseSet.Name, baseSet.ElementType.FullName)

             Dim associationSet As AssociationSet = _
                 TryCast(baseSet, AssociationSet)
             Dim end1 As AssociationSetEnd

             ' Iterate through the collection to get 
             ' each association end.
             For Each end1 In associationSet.AssociationSetEnds
               Console.WriteLine( _
                 "EntitySet Name: {0} , Name: {1}, AssociationEndMember: {2} ", _
                  end1.EntitySet, end1.Name, _
                  end1.CorrespondingAssociationEndMember)
               Next
         End If
      Next
    Next
  End Sub

  Public Shared Sub GetOneAssociationSet( _
    ByVal workspace As MetadataWorkspace, _
    ByVal relationshipName As String, _
    ByVal model As DataSpace)

    Console.WriteLine("***Get One AssociationSet =>")
    ' Get a collection of entity containers.
    Dim containers As ReadOnlyCollection(Of EntityContainer) = _
      workspace.GetItems(Of EntityContainer)(model)
    Dim container As EntityContainer

    ' Iterate through the collection to get each entity container.
    For Each container In containers
       Dim relationshipSet As RelationshipSet
       relationshipSet = Nothing
       ' Check if the relationship with the specified name exists 
       ' or not.
       If container.TryGetRelationshipSetByName( _
          relationshipName, True, relationshipSet) Then
          Dim associationSet As AssociationSet = _
            TryCast(relationshipSet, AssociationSet)
          Console.WriteLine( _
            "AssociationSet Name: {0} , AssociationType Name: {1} ", _
             associationSet.Name, associationSet.ElementType.FullName)
        End If
      Next
  End Sub
End Class

另请参见

概念

元数据类型层次结构