Using InverseProperty and ForeigKey Attribute

Microsoft keep simplifying things more and more. Today I will show you how to use InverseProperty and ForeignKey attribute to simplify our work with Entity Framework

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

Leave Comment

Your email address will not be published.

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box