Cómo definir un modelo con múltiples conjuntos de entidades por tipo (Entity Framework)
El Entity Data Model (EDM) permite incluir un tipo de entidad en múltiples conjuntos de entidades dentro de un solo contenedor de entidad o un tipo de entidad en varios conjuntos de entidades de varios contenedores de entidades. La definición de múltiples conjuntos de entidades por tipo (MEST, Multiple Entity Sets Per Type) permite a los usuarios mejorar su código cuando las bases de datos tienen particiones o en otros escenarios en los que varias tablas tienen la misma estructura. Para obtener más información, vea Conjuntos de entidades (EDM).
Para implementar el esquema conceptual del modelo de datos MEST
Cree un proyecto de biblioteca de clases y agregue una nueva plantilla EDM.
Implemente un tipo de entidad Customer que se incluya en dos conjuntos de entidades para los clientes del área oriental, CustomersEast, y del área occidental, CustomersWest.
Observe la diferencia entre el único tipo de entidad Customer, que se usa en dos conjuntos de entidades de clientes regionales, y los dos tipos de pedido, OrderEast y OrderWest, que se usan en los conjuntos de entidades OrdersEast y OrdersWest.
Implemente asociaciones entre el único tipo Customer y los dos tipos de pedidos regionales, OrderEast y OrderWest, para reflejar la estructura MEST. Ambas asociaciones entre el tipo Customer y los tipos de pedidos regionales especifican el Customer en el extremo de la asociación que tiene una cardinalidad de uno.
Implemente dos conjuntos de entidades que contengan el tipo Customer en el esquema del lenguaje de definición de esquemas conceptuales (CSDL, Conceptual Schema Definition Language). Los conjuntos de entidades CustomersEast y CustomersWest especifican ambos el RegionalCustomersModel.Customer como sus tipos de entidad.
<?xml version="1.0" encoding="utf-8"?>
<Schema Namespace="RegionalCustomersModel"
Alias="Self"
xmlns="https://schemas.microsoft.com/ado/2006/04/edm">
<EntityContainer Name="RegionalCustomersEntities">
<EntitySet Name="CustomersEast"
EntityType="RegionalCustomersModel.Customer" />
<EntitySet Name="CustomersWest"
EntityType="RegionalCustomersModel.Customer" />
<EntitySet Name="OrdersEast"
EntityType="RegionalCustomersModel.OrderEast" />
<EntitySet Name="OrdersWest"
EntityType="RegionalCustomersModel.OrderWest" />
<AssociationSet Name="FK_OrderEast_Customer"
Association="RegionalCustomersModel.FK_OrderEast_Customer">
<End Role="Customer" EntitySet="CustomersEast" />
<End Role="OrderEast" EntitySet="OrdersEast" />
</AssociationSet>
<AssociationSet Name="FK_OrderWest_Customer"
Association="RegionalCustomersModel.FK_OrderWest_Customer">
<End Role="Customer" EntitySet="CustomersWest" />
<End Role="OrderWest" EntitySet="OrdersWest" />
</AssociationSet>
</EntityContainer>
<EntityType Name="Customer">
<Key>
<PropertyRef Name="CustomerId" />
</Key>
<Property Name="CustomerId" Type="Int32" Nullable="false" />
<Property Name="Name" Type="String" Nullable="false" />
<Property Name="TotalPurchases" Type="Decimal" Nullable="false" />
<NavigationProperty Name="OrdersEast"
Relationship="RegionalCustomersModel.FK_OrderEast_Customer"
FromRole="Customer" ToRole="OrderEast" />
<NavigationProperty Name="OrdersWest"
Relationship="RegionalCustomersModel.FK_OrderWest_Customer"
FromRole="Customer" ToRole="OrderWest" />
</EntityType>
<EntityType Name="OrderEast">
<Key>
<PropertyRef Name="OrderId" />
</Key>
<Property Name="OrderId" Type="Int32" Nullable="false" />
<Property Name="OrderTotal"
Type="Decimal" Nullable="false" />
<Property Name="Tax" Type="Decimal" />
<NavigationProperty Name="Customer"
Relationship="RegionalCustomersModel.FK_OrderEast_Customer"
FromRole="OrderEast" ToRole="Customer" />
</EntityType>
<EntityType Name="OrderWest">
<Key>
<PropertyRef Name="OrderId" />
</Key>
<Property Name="OrderId" Type="Int32" Nullable="false" />
<Property Name="OrderTotal" Type="Decimal" Nullable="false" />
<Property Name="Tax" Type="Decimal" />
<NavigationProperty Name="Customer"
Relationship="RegionalCustomersModel.FK_OrderWest_Customer"
FromRole="OrderWest" ToRole="Customer" />
</EntityType>
<Association Name="FK_OrderEast_Customer">
<End Role="Customer"
Type="RegionalCustomersModel.Customer" Multiplicity="1" />
<End Role="OrderEast"
Type="RegionalCustomersModel.OrderEast" Multiplicity="*" />
</Association>
<Association Name="FK_OrderWest_Customer">
<End Role="Customer"
Type="RegionalCustomersModel.Customer" Multiplicity="1" />
<End Role="OrderWest"
Type="RegionalCustomersModel.OrderWest" Multiplicity="*" />
</Association>
</Schema>
Para implementar el esquema de almacenamiento para un modelo de datos MEST
Implemente tipos de entidad independientes correspondientes a las diferentes tablas de CustomerEast y CustomerWest.
Observe que hay dos tablas de clientes en el esquema de almacenamiento a diferencia del esquema conceptual del único tipo de entidad Customer.
<?xml version="1.0" encoding="utf-8"?>
<Schema Namespace="RegionalCustomersModel.Store"
Alias="Self"
Provider="System.Data.SqlClient"
ProviderManifestToken="2005"
xmlns="https://schemas.microsoft.com/ado/2006/04/edm/ssdl">
<EntityContainer Name="dbo">
<EntitySet Name="CustomerEast"
EntityType="RegionalCustomersModel.Store.CustomerEast" />
<EntitySet Name="CustomerWest"
EntityType="RegionalCustomersModel.Store.CustomerWest" />
<EntitySet Name="OrderEast"
EntityType="RegionalCustomersModel.Store.OrderEast" />
<EntitySet Name="OrderWest"
EntityType="RegionalCustomersModel.Store.OrderWest" />
<AssociationSet Name="FK_OrderEast_CustomerEast"
Association="RegionalCustomersModel.Store.FK_OrderEast_CustomerEast">
<End Role="CustomerEast" EntitySet="CustomerEast" />
<End Role="OrderEast" EntitySet="OrderEast" />
</AssociationSet>
<AssociationSet Name="FK_OrderWest_CustomerWest"
Association="RegionalCustomersModel.Store.FK_OrderWest_CustomerWest">
<End Role="CustomerWest" EntitySet="CustomerWest" />
<End Role="OrderWest" EntitySet="OrderWest" />
</AssociationSet>
</EntityContainer>
<EntityType Name="CustomerEast">
<Key>
<PropertyRef Name="CustomerId" />
</Key>
<Property Name="CustomerId" Type="int" Nullable="false" />
<Property Name="Name" Type="nvarchar"
Nullable="false" MaxLength="50" />
<Property Name="TotalPurchases" Type="money" Nullable="false" />
</EntityType>
<EntityType Name="CustomerWest">
<Key>
<PropertyRef Name="CustomerId" />
</Key>
<Property Name="CustomerId" Type="int" Nullable="false" />
<Property Name="Name" Type="nvarchar"
Nullable="false" MaxLength="50" />
<Property Name="TotalPurchases" Type="money" Nullable="false" />
</EntityType>
<EntityType Name="OrderEast">
<Key>
<PropertyRef Name="OrderId" />
</Key>
<Property Name="OrderId" Type="int" Nullable="false" />
<Property Name="CustomerId" Type="int" Nullable="false" />
<Property Name="OrderTotal" Type="money" Nullable="false" />
<Property Name="Tax" Type="money" />
</EntityType>
<EntityType Name="OrderWest">
<Key>
<PropertyRef Name="OrderId" />
</Key>
<Property Name="OrderId" Type="int" Nullable="false" />
<Property Name="CustomerId" Type="int" Nullable="false" />
<Property Name="OrderTotal" Type="money" Nullable="false" />
<Property Name="Tax" Type="money" />
</EntityType>
<Association Name="FK_OrderEast_CustomerEast">
<End Role="CustomerEast"
Type="RegionalCustomersModel.Store.CustomerEast" Multiplicity="1" />
<End Role="OrderEast" Type="RegionalCustomersModel.Store.OrderEast"
Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="CustomerEast">
<PropertyRef Name="CustomerId" />
</Principal>
<Dependent Role="OrderEast">
<PropertyRef Name="CustomerId" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_OrderWest_CustomerWest">
<End Role="CustomerWest"
Type="RegionalCustomersModel.Store.CustomerWest"
Multiplicity="1" />
<End Role="OrderWest"
Type="RegionalCustomersModel.Store.OrderWest"
Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="CustomerWest">
<PropertyRef Name="CustomerId" />
</Principal>
<Dependent Role="OrderWest">
<PropertyRef Name="CustomerId" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema>
Para generar la base de datos mediante SQL Server Management Studio
Use el siguiente script con SQL Server Management Studio para generar la base de datos que se usa en este ejemplo y en el ejemplo de Cómo definir un modelo con herencia de tabla por tipo (Entity Framework).
Seleccione Nuevo en el menú Archivo y haga clic en Consulta de motor de base de datos para crear la base de datos SchoolData y el esquema con SQL Server Management Studio.
Escriba el
localhost
o el nombre de otra instancia de SQL Server en el cuadro de diálogo Conectarse al motor de base de datos y haga clic en Conectar.Pegue el siguiente script de Transact-SQL en la ventana de consulta y, a continuación, haga clic en Ejecutar.
USE [master]
GO
CREATE DATABASE [RegionalCustomersMEST]
GO
USE [RegionalCustomersMEST]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustomerWest]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CustomerWest](
[CustomerId] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[TotalPurchases] [money] NOT NULL,
CONSTRAINT [PK_CustomerWest] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustomerEast]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CustomerEast](
[CustomerId] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[TotalPurchases] [money] NOT NULL,
CONSTRAINT [PK_CustomerEast] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OrderWest]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OrderWest](
[OrderId] [int] NOT NULL,
[CustomerId] [int] NOT NULL,
[OrderTotal] [money] NOT NULL,
[Tax] [money] NULL,
CONSTRAINT [PK_OrderWest] PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OrderEast]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OrderEast](
[OrderId] [int] NOT NULL,
[CustomerId] [int] NOT NULL,
[OrderTotal] [money] NOT NULL,
[Tax] [money] NULL,
CONSTRAINT [PK_OrderEast] PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderWest_CustomerWest]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderWest]'))
ALTER TABLE [dbo].[OrderWest] WITH CHECK ADD CONSTRAINT [FK_OrderWest_CustomerWest] FOREIGN KEY([CustomerId])
REFERENCES [dbo].[CustomerWest] ([CustomerId])
GO
ALTER TABLE [dbo].[OrderWest] CHECK CONSTRAINT [FK_OrderWest_CustomerWest]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderEast_CustomerEast]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderEast]'))
ALTER TABLE [dbo].[OrderEast] WITH CHECK ADD CONSTRAINT [FK_OrderEast_CustomerEast] FOREIGN KEY([CustomerId])
REFERENCES [dbo].[CustomerEast] ([CustomerId])
GO
ALTER TABLE [dbo].[OrderEast] CHECK CONSTRAINT [FK_OrderEast_CustomerEast]
Para implementar la especificación de la asignación para el modelo MEST
Asigne la única entidad Customer para independizar las tablas de CustomerEast y de CustomerWest como se ilustra a continuación.
Observe los conjuntos de entidades independientes para CustomersEast y CustomersWest en la asignación del contenedor de entidades.
<?xml version="1.0" encoding="utf-8"?>
<Mapping Space="C-S"
xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">
<EntityContainerMapping
StorageEntityContainer="dbo"
CdmEntityContainer="RegionalCustomersEntities">
<EntitySetMapping Name="CustomersEast">
<EntityTypeMapping TypeName="RegionalCustomersModel.Customer">
<MappingFragment StoreEntitySet="CustomerEast">
<ScalarProperty Name="CustomerId" ColumnName="CustomerId" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="TotalPurchases"
ColumnName="TotalPurchases" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="CustomersWest">
<EntityTypeMapping TypeName="RegionalCustomersModel.Customer">
<MappingFragment StoreEntitySet="CustomerWest">
<ScalarProperty Name="CustomerId" ColumnName="CustomerId" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="TotalPurchases"
ColumnName="TotalPurchases" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="OrdersEast" StoreEntitySet="OrderEast"
TypeName="RegionalCustomersModel.OrderEast">
<ScalarProperty Name="OrderId" ColumnName="OrderId" />
<ScalarProperty Name="OrderTotal" ColumnName="OrderTotal" />
<ScalarProperty Name="Tax" ColumnName="Tax" />
</EntitySetMapping>
<EntitySetMapping Name="OrdersWest" StoreEntitySet="OrderWest"
TypeName="RegionalCustomersModel.OrderWest">
<ScalarProperty Name="OrderId" ColumnName="OrderId" />
<ScalarProperty Name="OrderTotal" ColumnName="OrderTotal" />
<ScalarProperty Name="Tax" ColumnName="Tax" />
</EntitySetMapping>
<AssociationSetMapping Name="FK_OrderEast_Customer"
TypeName="RegionalCustomersModel.FK_OrderEast_Customer"
StoreEntitySet="OrderEast">
<EndProperty Name="Customer">
<ScalarProperty Name="CustomerId" ColumnName="CustomerId" />
</EndProperty>
<EndProperty Name="OrderEast">
<ScalarProperty Name="OrderId" ColumnName="OrderId" />
</EndProperty>
<Condition ColumnName="CustomerId" IsNull="false" />
</AssociationSetMapping>
<AssociationSetMapping Name="FK_OrderWest_Customer"
TypeName="RegionalCustomersModel.FK_OrderWest_Customer"
StoreEntitySet="OrderWest">
<EndProperty Name="Customer">
<ScalarProperty Name="CustomerId" ColumnName="CustomerId" />
</EndProperty>
<EndProperty Name="OrderWest">
<ScalarProperty Name="OrderId" ColumnName="OrderId" />
</EndProperty>
<Condition ColumnName="CustomerId" IsNull="false" />
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping>
Vea también
Tareas
Cómo crear y ejecutar consultas de objeto con múltiples conjuntos de entidades por tipo (Entity Framework)
Cómo agregar un objeto a un conjunto de entidades específico (Entity Framework)