entity-framework/ef6/modeling/designer/entity-splitting.md
This walkthrough shows how to map an entity type to two tables by modifying a model with the Entity Framework Designer (EF Designer). You can map an entity to multiple tables when the tables share a common key. The concepts that apply to mapping an entity type to two tables are easily extended to mapping an entity type to more than two tables.
The following image shows the main windows that are used when working with the EF Designer.
Visual Studio 2012 or Visual Studio 2010, Ultimate, Premium, Professional, or Web Express edition.
The database server that is installed with Visual Studio is different depending on the version of Visual Studio you have installed:
First we'll create a database with two tables that we are going to combine into a single entity.
CREATE TABLE [dbo].[Person] (
[PersonId] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (200) NULL,
[LastName] NVARCHAR (200) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ([PersonId] ASC)
);
CREATE TABLE [dbo].[PersonInfo] (
[PersonId] INT NOT NULL,
[Email] NVARCHAR (200) NULL,
[Phone] NVARCHAR (50) NULL,
CONSTRAINT [PK_PersonInfo] PRIMARY KEY CLUSTERED ([PersonId] ASC),
CONSTRAINT [FK_Person_PersonInfo] FOREIGN KEY ([PersonId]) REFERENCES [dbo].[Person] ([PersonId]) ON DELETE CASCADE
);
The Entity Designer, which provides a design surface for editing your model, is displayed.
In this step we will update the Person entity type to combine data from the Person and PersonInfo tables.
Select the Email and Phone properties of the **PersonInfo **entity and press Ctrl+X keys.
Select the **Person **entity and press Ctrl+V keys.
On the design surface, select the PersonInfo entity and press Delete button on the keyboard.
Click No when asked if you want to remove the PersonInfo table from the model, we are about to map it to the Person entity.
The next steps require the Mapping Details window. If you cannot see this window, right-click the design surface and select Mapping Details.
The Person entity type is now mapped to the Person and PersonInfo tables.
using (var context = new EntitySplittingEntities())
{
var person = new Person
{
FirstName = "John",
LastName = "Doe",
Email = "[email protected]",
Phone = "555-555-5555"
};
context.People.Add(person);
context.SaveChanges();
foreach (var item in context.People)
{
Console.WriteLine(item.FirstName);
}
}
The following T-SQL statements were executed against the database as a result of running this application.
The following two INSERT statements were executed as a result of executing context.SaveChanges(). They take the data from the Person entity and split it between the Person and PersonInfo tables.
The following SELECT was executed as a result of enumerating the people in the database. It combines the data from the Person and PersonInfo table.