Cómo: Definir un modelo con herencia de tabla por tipo (Entity Framework)

En este tema se describe cómo crear de forma manual un modelo conceptual que tiene una jerarquía de herencia de tabla por tipo. La herencia de tabla por tipo usa una tabla independiente de la base de datos para mantener los datos de las propiedades no heredadas y de las propiedades de clave para cada tipo de la jerarquía de herencia.

Bb738685.note(es-es,VS.100).gifNota:
El método recomendado para definir un modelo con una herencia de tabla por tipo es utilizar ADO.NET Entity Data Model Tools.Para obtener más información, vea Walkthrough: Mapping Inheritance - Table-per-Type.

Los pasos básicos para definir manualmente un modelo con una herencia de tabla por tipo son los siguientes:

  1. Defina un conjunto de entidades en el modelo conceptual que contendrá el tipo de entidad base y los tipos derivados. Para obtener más información, vea EntitySet (Elemento) (CSDL).

  2. Defina los tipos de entidad derivada en el modelo conceptual mediante el atributo BaseType y defina solo propiedades no heredadas en los tipos derivados. Para obtener más información, vea EntityType (Elemento) (CSDL).

  3. Asigne el tipo de entidad base y los tipos derivados del mismo elemento EntitySetMapping en el lenguaje de especificación de asignaciones (MSL). Asigne propiedades heredadas a columnas de tabla cuando resulte adecuado. Utilice la sintaxis IsTypeOf al establecer el valor del atributo TypeName. Para obtener más información, vea EntitySetMapping (Elemento) (MSL).

El siguiente ejemplo supone que ha instalado la base de datos de ejemplo School y que ha configurado manualmente el proyecto para que utilice Entity Framework . Para obtener más información, vea Crear la aplicación de ejemplo School (Tutorial rápido de Entity Framework) y Configurar Entity Framework (tareas de Entity Framework).

Para crear el modelo de almacenamiento

  1. Agregue el siguiente archivo XML a su proyecto y denomínelo School.ssdl.

    <?xml version="1.0" encoding="utf-8" ?>
    <Schema Namespace="SchoolModel.Store" Alias="Self" Provider="System.Data.SqlClient"
                  ProviderManifestToken="2008"
                  xmlns:store="https://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"
                  xmlns="https://schemas.microsoft.com/ado/2009/02/edm/ssdl">
      <EntityContainer Name="SchoolModelStoreContainer">
        <EntitySet Name="Course" EntityType="SchoolModel.Store.Course"
                   store:Type="Tables" Schema="dbo" />
        <EntitySet Name="OnlineCourse" EntityType="SchoolModel.Store.OnlineCourse"
                   store:Type="Tables" Schema="dbo" />
        <EntitySet Name="OnsiteCourse" EntityType="SchoolModel.Store.OnsiteCourse"
                   store:Type="Tables" Schema="dbo" />
      </EntityContainer>
      <EntityType Name="Course">
        <Key>
          <PropertyRef Name="CourseID" />
        </Key>
        <Property Name="CourseID" Type="int" Nullable="false" />
        <Property Name="Title" Type="nvarchar" Nullable="false" MaxLength="100" />
        <Property Name="Credits" Type="int" Nullable="false" />
        <Property Name="DepartmentID" Type="int" Nullable="false" />
      </EntityType>
      <EntityType Name="OnlineCourse">
        <Key>
          <PropertyRef Name="CourseID" />
        </Key>
        <Property Name="CourseID" Type="int" Nullable="false" />
        <Property Name="URL" Type="nvarchar" Nullable="false" MaxLength="100" />
      </EntityType>
      <EntityType Name="OnsiteCourse">
        <Key>
          <PropertyRef Name="CourseID" />
        </Key>
        <Property Name="CourseID" Type="int" Nullable="false" />
        <Property Name="Location" Type="nvarchar" Nullable="false" MaxLength="50" />
        <Property Name="Days" Type="nvarchar" Nullable="false" MaxLength="50" />
        <Property Name="Time" Type="smalldatetime" Nullable="false" />
      </EntityType>
    </Schema>
    

Para crear el modelo conceptual

  1. Agregue el siguiente archivo XML a su proyecto y denomínelo School.csdl. Tenga en cuenta los siguientes extremos:

    • Solo se define un conjunto de entidades, Courses, para los tres tipos de entidad: Course, OnlineCourse y OnsiteCourse.

    • Los tipos de entidad OnsiteCourse y OnlineCourse son tipos derivados como indica el atributo BaseType de sus definiciones.

    • Las propiedades definidas para los tipos de entidad OnsiteCourse y OnlineCourse son exclusivamente propiedades no heredadas.

    <?xml version="1.0" encoding="utf-8" ?>
    <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="Courses" EntityType="SchoolModel.Course" />
      </EntityContainer>
      <EntityType Name="Course">
        <Key>
          <PropertyRef Name="CourseID" />
        </Key>
        <Property Name="CourseID" Type="Int32" Nullable="false" />
        <Property Name="Title" Type="String" Nullable="false"
                  MaxLength="100" Unicode="true" FixedLength="false" />
        <Property Name="Credits" Type="Int32" Nullable="false" />
        <Property Name="DepartmentID" Type="Int32" Nullable="false" />
      </EntityType>
      <EntityType Name="OnlineCourse" BaseType="SchoolModel.Course">
        <Property Name="URL" Type="String" Nullable="false"
                  MaxLength="100" Unicode="true" FixedLength="false" />
      </EntityType>
      <EntityType Name="OnsiteCourse" BaseType="SchoolModel.Course">
        <Property Name="Location" Type="String" Nullable="false"
                  MaxLength="50" Unicode="true" FixedLength="false" />
        <Property Name="Days" Type="String" Nullable="false"
                  MaxLength="50" Unicode="true" FixedLength="false" />
        <Property Name="Time" Type="DateTime" Nullable="false" />
      </EntityType>
    </Schema>
    

Para definir la asignación entre el modelo conceptual y el modelo de almacenamiento

  1. Agregue el siguiente archivo XML a su proyecto y denomínelo School.msl. Tenga en cuenta los siguientes extremos:

    • La asignación de Course, OnlineCoursey los tipos de entidad OnsiteCourse se define en el mismo elemento EntitySetMapping.

    • Las propiedades CourseID heredadas para OnlineCourse y OnsiteCourse se asignan a las columnas correspondientes en las tablas de base de datos subyacentes.

    • Para cada asignación de tipo de entidad, se utiliza la sintaxis IsTypeOf para indicar el tipo de entidad que se está asignando.

    <?xml version="1.0" encoding="utf-8" ?>
    <Mapping Space="C-S" xmlns="https://schemas.microsoft.com/ado/2008/09/mapping/cs">
      <EntityContainerMapping StorageEntityContainer="SchoolModelStoreContainer"
                              CdmEntityContainer="SchoolEntities">
        <EntitySetMapping Name="Courses">
          <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Course)">
            <MappingFragment StoreEntitySet="Course">
              <ScalarProperty Name="CourseID" ColumnName="CourseID" />
              <ScalarProperty Name="Title" ColumnName="Title" />
              <ScalarProperty Name="Credits" ColumnName="Credits" />
              <ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" />
            </MappingFragment>
          </EntityTypeMapping>
          <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.OnlineCourse)">
            <MappingFragment StoreEntitySet="OnlineCourse">
              <ScalarProperty Name="CourseID" ColumnName="CourseID" />
              <ScalarProperty Name="URL" ColumnName="URL" />
            </MappingFragment>
          </EntityTypeMapping>
          <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.OnsiteCourse)">
            <MappingFragment StoreEntitySet="OnsiteCourse">
              <ScalarProperty Name="CourseID" ColumnName="CourseID" />
              <ScalarProperty Name="Location" ColumnName="Location" />
              <ScalarProperty Name="Days" ColumnName="Days" />
              <ScalarProperty Name="Time" ColumnName="Time" />
            </MappingFragment>
          </EntityTypeMapping>
        </EntitySetMapping>
      </EntityContainerMapping>
    </Mapping>
    

Vea también

Tareas

Cómo definir un modelo con herencia de tabla por jerarquía (Entity Framework)

Otros recursos

Especificaciones CSDL, SSDL y MSL
Entity Data Model: Inheritance
Definir modelos de datos avanzados (tareas de Entity Framework)