This is the third part of my Entity Framework Code First Tutorial for beginners. If you want to start fresh , Visit the first part here.
Entity Framework Code First has some nice conventions to follow when you want to work with relationships. Let’s see how it works.
If your class contains a reference and a collection nvigation property, EF will create a One-tp-Many relationshop. The navigation property need to be at only side(class) to get this one to many relation ship to be working.
Let’t take the customer class from our part 2 source code. We will create a new model class for Address.
Now we will add a Navigational property to our Customer class. Since one customer can have multiple Addresses, We can add a Collection property.
Now, Entity framework CodeFirst is going to create a new table for me to store the Addresses and it will have a Column to store the CustomerID. The convention for the name of the column is the “PrimaryKeyTableName_PrimaryKeyNameOfPrimaryKeyTable“.
The output is
Now We can fill the collection property to save the Addresses while creating a new customer. Let’s update the HttpPost Create action method like this.
We can also use Data Annotations also to define the Relationship, if you are not following the Convention (naming of the properties).I may explain it later in a different post.