Walkthrough: Adding Entities Using Foreign Key Properties (Entity Framework)
This topic describes how to generate a conceptual model with foreign keys exposed as entity properties and how to write code for creating entities and relationships.
Starting with Visual Studio 2010, when you generate a model from an existing database, the ADO.NET Entity Data Model Designer (Entity Designer) creates scalar properties on entity types that correspond to foreign key columns in the database. Foreign key properties can be used to create and modify relationships between entity types. By default, the Entity Designer also generates navigation properties on entity types that can be used to create and modify relationships. This walkthrough demonstrates how to create relationships by using both foreign key properties and navigation properties. Creating and managing relationships by using foreign key properties simplifies many common scenarios. For example, data binding, concurrency control, and n-tier scenarios can be made simpler by using foreign key properties to create and manage relationships. For more information, see Defining and Managing Relationships (Entity Framework).
Prerequisites
To complete this walkthrough, you must have Visual Studio 2010 or later installed on your computer and you must have access to a SQL Server instance that contains the School sample database. For more information, see Creating the School Sample Database (Entity Framework Quickstart).
This walkthrough assumes that you have basic competency with Visual Studio, the .NET Framework, and programming in either Visual C# or Visual Basic.
Generating the .edmx File
To complete this procedure, you must have a new WPF Application project open in Visual Studio. In this procedure, you will generate an .edmx file based on two tables in the School sample database. An .edmx file contains a conceptual model, storage model, and the mapping between them. For more information, see .edmx File Overview (Entity Framework). Entity types in the generated conceptual model will have scalar properties that correspond to foreign key columns in the database.
To generate the .edmx file
In Solution Explorer, right-click the project name, point to Add, and select New Item.
The Add New Item dialog box appears.
Select ADO.NET Entity Data Model and click Add. (To reduce the number of visible templates, choose Data under Installed Templates.)
In the Entity Data Model Wizard, select Generate from Database and click Next.
In the Choose Your Data Connection Dialog Box, connect to the School sample database and click Next.
In the Choose Your Database Objects Dialog Box, expand the Tables node and select the Course and Department tables. Note that the Pluralize or singularize generated object names and Include foreign key columns in the model check boxes are selected by default. Leaving the Include foreign key columns in the model checkbox selected will create scalar properties on entity types that are mapped to foreign key columns in the database and foreign key associations are created between entities. Clearing this check box will cause independent associations to be created between entity types. For more information, see Association Element (CSDL) and ReferentialConstraint Element (CSDL).
Leaving the Pluralize or singularize generated object names checkbox selected will apply English language rules for plurals and singulars to entity set, entity type, and navigation property names. For more information, see Choose Your Database Objects Dialog Box (Entity Data Model Wizard).
This walkthrough assumes that you proceed with both checkboxes selected.
Click Finish.
An .edmx file is added to your project and is displayed in the Entity Designer. The display shows two entity types (Department and Course) with one-to-many (1:*) association between them. The association is created using a referential constraint and can be viewed by opening the .edmx file in the XML Editor:
<Association Name="FK_Course_Department"> <End Role="Department" Type="SchoolModel.Department" Multiplicity="1" /> <End Role="Course" Type="SchoolModel.Course" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Department"> <PropertyRef Name="DepartmentID" /> </Principal> <Dependent Role="Course"> <PropertyRef Name="DepartmentID" /> </Dependent> </ReferentialConstraint> </Association>
For more information, see ReferentialConstraint Element (CSDL).
Creating the User Interface
In this procedure you add controls to your application that allow you to create and update information about departments and courses.
To create the user interface
From the Visual Studio Data menu, select Show Data Sources.
The Data Sources pane appears.
Click on the
MainWindow.xaml
tab to show the MainWindow design surface.In the Data Sources pane, click on the Courses data source and select Details from the drop-down list.
Repeat step two for the Departments data source.
In the Data Sources pane, expand the Courses data source, click the DepartmentID field, and select None.
In the Data Sources pane, expand the Departments data source, click the Name field, and select ComboBox.
Drag the Courses and Departments data sources onto the MainWindow design surface.
Grid controls for the Courses and Departments data source are created on the MainWindow design surface.
Clear the IsEnabled checkbox in the Properties window for the Department ID, Budget, Start Date, and Administrator text boxes.
Select the IsEditable checkbox in the Properties window for the Name combo box.
From the Toolbox, drag a Checkbox control on to the MainWindow design surface. Change the name of the Checkbox control to
newDepartment
and set its Content property to New Department.From the Toolbox, drag a Button control to the MainWindow design surface. Change the name of the Button control to
addWithFKButton
, and change its Content property to Add (FK).From the Toolbox, drag a Button control to the MainWindow design surface. Change the name of the Button control to
addWithNavPropButton
, and change its Content property to Add (Nav Prop).
The user interface is now complete.
Adding Related Entities By Using Foreign Key Properties
In this procedure you will add code to your application that will allow you to add a new courses and departments by using foreign key properties.
To add related entities by using foreign key properties
Open the
MainWindow.xaml.vb
orMainWindow.xaml.cs
file and add the following Using (C#) or Imports (Visual Basic) statement:Imports System.Data.Objects
using System.Data.Objects;
Add the following member to the
MainWindow
class. This is the ObjectContext to which you will add objects.Private context As SchoolEntities
private SchoolEntities context;
Replace the code in the
Window_Loaded
method with the following code that populates a GridView control with departments:context = New SchoolEntities() Dim departmentsViewSource As CollectionViewSource = _ DirectCast((Me.FindResource("DepartmentsViewSource")), _ CollectionViewSource) Dim departmentsQuery As ObjectQuery(Of Department) = _ Me.GetDepartmentsQuery(context) departmentsViewSource.Source = _ departmentsQuery.Execute(MergeOption.AppendOnly)
context = new SchoolEntities(); CollectionViewSource departmentsViewSource = ((CollectionViewSource)(this.FindResource("departmentsViewSource"))); ObjectQuery<Department> departmentsQuery = this.GetDepartmentsQuery(context); departmentsViewSource.Source = departmentsQuery.Execute(MergeOption.AppendOnly);
On the MainWindow design surface, double-click the New Department button.
The
newDepartment_Checked
method is added to the code-behind file.Add the following code to the
newDepartment_Checked
method. This will allow you to add a new department to the ObjectContext.Dim departmentsViewSource As CollectionViewSource = _ DirectCast((FindResource("DepartmentsViewSource")), _ CollectionViewSource) If newDepartment.IsChecked = True Then departmentsViewSource.Source = Nothing DepartmentIDTextBox.IsEnabled = True BudgetTextBox.IsEnabled = True StartDateDatePicker.IsEnabled = True AdministratorTextBox.IsEnabled = True End If
CollectionViewSource departmentsViewSource = (CollectionViewSource)(FindResource("departmentsViewSource")); if (newDepartment.IsChecked == true) { departmentsViewSource.Source = null; departmentIDTextBox.IsEnabled = true; budgetTextBox.IsEnabled = true; startDateDatePicker.IsEnabled = true; administratorTextBox.IsEnabled = true; }
On the MainWindow design surface, double click the Add (FK) button.
The
addWithFKButton_Click
method is added to the code-behind file.Add the following code to the
addWithFKButton_Click
method. Note that a new course is associated with a department by setting the DepartmentID property of the new course.If newDepartment.IsChecked = True Then Dim dept As New Department() dept.DepartmentID = Convert.ToInt32(DepartmentIDTextBox.Text) dept.Name = NameComboBox.Text dept.Budget = Convert.ToInt32(BudgetTextBox.Text) dept.StartDate = Convert.ToDateTime(StartDateDatePicker.SelectedDate) dept.Administrator = Convert.ToInt32(AdministratorTextBox.Text) context.Departments.AddObject(dept) End If Dim course As New Course() course.CourseID = Convert.ToInt32(CourseIDTextBox.Text) course.Title = TitleTextBox.Text course.Credits = Convert.ToInt32(CreditsTextBox.Text) ' The new course is associated with a department ' by setting the DepartmentID property. course.DepartmentID = Convert.ToInt32(DepartmentIDTextBox.Text) context.Courses.AddObject(course) context.SaveChanges()
if (newDepartment.IsChecked == true) { Department dept = new Department { DepartmentID = Convert.ToInt32(departmentIDTextBox.Text), Name = nameComboBox.Text, Budget = Convert.ToInt32(budgetTextBox.Text), StartDate = Convert .ToDateTime(startDateDatePicker.SelectedDate), Administrator = Convert .ToInt32(administratorTextBox.Text) }; context.Departments.AddObject(dept); } Course course = new Course { CourseID = Convert.ToInt32(courseIDTextBox.Text), Title = titleTextBox.Text, Credits = Convert.ToInt32(creditsTextBox.Text), // The new course is associated with a department // by setting the DepartmentID property. DepartmentID = Convert.ToInt32(departmentIDTextBox.Text) }; context.Courses.AddObject(course); context.SaveChanges();
Note |
---|
If you add a new course and a new department at the same time, their navigation properties are not synchronized until SaveChanges has been called. For example, if you try to access the new department through the navigation property on the new course before calling SaveChanges, null is returned. |
Press Crtl+F5 to run the program. You can add a new course to the selected department by editing course information and clicking Add (FK). You can add a new course to a new department by checking the New Department checkbox, editing course and department information, and clicking Add (FK).
Adding Related Entities by Using Navigation Properties
In this procedure you will add code to your application that allows you to add new courses and departments by using navigation properties.
Procedure Title
On the MainWindow design surface, double click the Add (Nav Prop) button.
The
addWithNavPropButton_Click
method is added to the code-behind file.Add the following code to the
addWithNavPropButton_Click
method. Note that a new course is associated with a department by setting the Department navigation property of the new course. This also adds the new course to the ObjectContext.Dim dept As Department If newDepartment.IsChecked = True Then dept = New Department() dept.DepartmentID = Convert.ToInt32(DepartmentIDTextBox.Text) dept.Name = NameComboBox.Text dept.Budget = Convert.ToInt32(BudgetTextBox.Text) dept.StartDate = Convert.ToDateTime(StartDateDatePicker.SelectedDate) dept.Administrator = Convert.ToInt32(AdministratorTextBox.Text) context.Departments.AddObject(dept) Else dept = DirectCast(NameComboBox.SelectedItem, Department) End If Dim course As New Course() course.CourseID = Convert.ToInt32(CourseIDTextBox.Text) course.Title = TitleTextBox.Text course.Credits = Convert.ToInt32(CreditsTextBox.Text) ' The new course is associated with a department ' by setting the Department navigation property. ' This also adds the new course to the context. course.Department = dept context.Courses.AddObject(course) context.SaveChanges()
Department dept; if (newDepartment.IsChecked == true) { dept = new Department { DepartmentID = Convert.ToInt32(departmentIDTextBox.Text), Name = nameComboBox.Text, Budget = Convert.ToInt32(budgetTextBox.Text), StartDate = Convert .ToDateTime(startDateDatePicker.SelectedDate), Administrator = Convert.ToInt32(administratorTextBox.Text) }; context.Departments.AddObject(dept); } else { dept = (Department)nameComboBox.SelectedItem; } Course course = new Course { CourseID = Convert.ToInt32(courseIDTextBox.Text), Title = titleTextBox.Text, Credits = Convert.ToInt32(creditsTextBox.Text), // The new course is associated with a department // by setting the Department navigation property. // This also adds the new course to the context. Department = dept }; context.SaveChanges();
Press Crtl+F5 to run the program. You can add a new course to the selected department by editing course information and clicking Add (Nav Prop). You can add a new course to a new department by checking the New Department checkbox, editing course and department information, and clicking Add (Nav Prop).
See Also
Tasks
How to: Create a New .edmx File (Entity Data Model Tools)