Using InverseProperty and ForeignKey Attributes

InverseProperty and ForeignKey are (arguably) the most commonly used attribues in Entity Framework when developing in code-first approach. They help greatly simply the job of managing our models.

Foreign Key

In order to introduce foreign key to our code we need to specify to what objects it maps to. So there are two things that have be done:

  1. Define ID for the database use
  2. Define the object to which it maps using [ForeignKey] attribute

Note: virtual informs CLR that we are using lazy evaluation i.e. the object will be fetched only if/when we need it. I have to admit this is a heady feature, no longer need to fetch the object myself.

Massive time saver

Inverse Property

InverseProperty is even more impressive, because it allows you to fetch many "dependant" objects from the database as a List e.g. Posts written by someone.

It took me a while to spot the pattern here:

  1. We are referring to class Post
  2. from class Person
  3. to property Author