Getting started with EF Core

Add Vehicle

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 shadow 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)

Last updated