EF Code First Example

Entity Framework (EF) recently started supporting code-first development. This means that we don't have to create our database first before we can write any code. It allows developers to create their models (business entities, data objects etc) and then it will automatically create the database after very little configuration. I wanted to see how EF handles relationships. So I created this sample to demonstrate how EF code first handles many-to-many relationship.
For my app, the scenario is very simple. We have Person and Address entities. A person can have many addresses and an Address can belong to many persons. So, its a many to many relationship. To get up and running with an app, all the code I needed to write was this.
I also needed to make a small entry for connection string in the app.config as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="CodeFirstContext" 
         connectionString="Data Source=|DataDirectory|CodeFirst.sdf"
         providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>
</configuration>
In the database, you can see that EF created Persons, Addresses and AddressPersons table (junction table) to achieve many-to-many relationship.

If you see the code, all the code in main function is just trying to do CRUD operations to the DB. But to get the DB up and running we needed to write very little code. Also, for this code to work you will have to get the latest EF Code First package using Nuget. The output of this program is shown below -

No comments: