How associations are mapped when using Code First with Entity Framework

Mapping single class with a table was bit easy and fun. Next should be mapping associations, first I will try to map a simple one, using our existing application code. A person can have multiple email addresses.

So here is the modified code for person

Then I created the required EmailItem class, with relevant mapping configurations.

Made some changes in context related class as below.

Then just attached an email to a person in our test as below

Hmm, lets look at the schema which is now generated after all these changes.

association mapping

look there, table for holding emails has been generated, and it has been linked to people table too. A foreign key is automatically generated, although the name is not quite to our liking. Lets look at how to do that. Just make following changes in person configuration class, and you will have what you want.

1 thought on “How associations are mapped when using Code First with Entity Framework

Leave a Reply to shahzad aslam Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.