Working with Foreign Keys
Starting with the .NET Framework version 4, you can expose foreign key properties on entity types and define relationships through foreign keys. The Include foreign key columns in the model option in the Entity Data Model Wizard is selected by default. When this option is selected, the generated entity objects have scalar properties that map to foreign key columns.
Foreign key properties allow you to create or modify a relationship without querying for the principal object. When you include foreign key properties, you can still modify a relationship by updating the reference to the principal object on the dependent or adding a dependent object to a collection on the principal object. A common way to access references and collections on entities is through navigation properties. For more information, see Navigation Properties.
The Entity Framework tries to keep references, collections, and foreign key properties in sync. If you update a foreign key property of a dependent object, the reference on this object and the collection on the principal object should be synchronized. For this synchronization to occur, the entities must be attached to the object context and the entities must be tracked by the Entity Framework. For more information, see Identity Resolution, State Management, and Change Tracking and Defining and Managing Relationships.
The examples in this topic are based on the School Model. The entity types in these examples are generated by the Entity Data Model tools. The generated types are tracked by the Entity Framework. If you are working with POCO types, see Tracking Changes in POCO Entities.
The following example shows how to change the relationship between two existing objects.
The following example shows how to set the relationship between the new dependent object and existing principal objects by setting the foreign key properties.
The following example shows how to set the relationship between the new dependent and new principal object.
With foreign keys association, you can still use the reference to set the relationship as you would do in the version prior to the Entity Framework 4.
The following demonstrates a simple communication between a client and a service, where the client requests an object from the service, the client updates the object and calls the service to save the changes to the database.
The service defines two methods:
The client updates the values of the foreign key properties and sends the updated object to the service: