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:
- Define ID for the database use
- Define the object to which it maps using [ForeignKey] attribute
1 2 3 4 5 |
//Define the foreign key as an int that is used by the database public int Table2ID { get; set; } //Now we need to define the object to which it maps [ForeignKey("Table2ID")] public virtual Table2Object Table2Object { get; set; } |
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.
1 2 3 4 5 |
var query = from table2object in Table2Objects where table2object.Table1ID == ... select table2object; Table2Object object1 = query.FirstOrDefault(); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Post { public int PostID { get; set; } public Person Author { get; set; } } class Person { public int PersonID { get; set; } [InverseProperty("Author")] public List<Post> Posts { get; set; } } |
It took me a while to spot the pattern here:
- We are referring to class
Post
- from class
Person
- to property
Author