EF Core
Getting started with EF Core
Getting started with EF Core
  • Introduction
    • What is an ORM
    • Entity Framework Core
    • EF Core architecture
    • EF Core Approaches
  • Basics of EF Core
    • Create the project
      • Create the model & context
    • Create migration
    • CRUD using EF
      • Creating many entities
      • Update & Delete
    • Adding a property
      • Add migration
  • Entity Relationships
    • Add related entity
      • Add Vehicle
      • Modify Student
      • Modify context
      • Add migration
    • Manipulate related data
  • Entity Configuration
    • Fluent APIs
      • Frequently used APIs
    • Data Annotations
      • Frequently used annotations
Powered by GitBook
On this page
  1. Entity Relationships
  2. Add related entity

Add Vehicle

PreviousAdd related entityNextModify Student

Last updated 2 years ago

Let's add a related entity

Continuing our discussion of the previous project where we have only one entity called student let us add one more entity called vehicle. Let's say we are trying to capture a requirement where a student can bring any number of vehicles to the college campus as long as it has been registered with the authorities

Add vehicle class and replace the contents with the one below

namespace EFGetStarted
{
    public class Vehicle
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int StudentId { get; set; }
        public Student Student { get; set; }
    }
}

note the following here

  • the StudentId property is called the foreign key property

    • when such conventions are followed EF automatically creates foreign keys accordingly in the database!

  • it is recommended to include the foreign key property

    • if not included a foreign key property will be introduced by EF

  • the Student property is a (reference) navigation property

    • data type and the property name (Student) are the same here, it is advised to follow this convention!

  • In legacy EF, navigation properties were prefixed with virtual modifier; it is not required in EF core

    • lazy loading is discouraged and hence virtual is not required, more on this later

If we do not follow conventions for any reason, we will have to explicitly configure the entities (discussed later)

shadow