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.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace CodeFirst
{
    class Program
    {
        static void Main(string[] args)
        {
            var ctx = new CodeFirstContext();

            //add few persons
            ctx.Persons.Add(new Person { Name = "Lionel Messi" });
            ctx.Persons.Add(new Person { Name = "Rafael Nadal" });
            ctx.SaveChanges();

            // add few addresses
            ctx.Addresses.Add(new Address {City = "Barcelona"});
            ctx.SaveChanges();

            //get Messi
            var person = ctx.Persons.Where(p => p.Name.StartsWith("Lionel")).SingleOrDefault();
            var addr = ctx.Addresses.Where(a => a.City == "Barcelona").SingleOrDefault();
            person.Addresses = new List<Address>();
            person.Addresses.Add(addr);
            person.Addresses.Add(new Address{City = "Mallorca"});
            ctx.SaveChanges();

            // get Nadal
            person = ctx.Persons.Where(p => p.Name.StartsWith("Rafael")).SingleOrDefault();
            addr = ctx.Addresses.Where(a => a.City == "Mallorca").SingleOrDefault();
            person.Addresses = new List<Address>();
            person.Addresses.Add(addr);
            ctx.SaveChanges();
           
            //get all
            var persons = ctx.Persons.Include("Addresses");

            foreach(var p in persons)
            {
                Console.WriteLine("\n" + p.Id + "   " + p.Name);
                foreach(var a in p.Addresses)
                    Console.WriteLine("\t" + a.Id + "    " + a.City);
            }

            Console.Read();
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public List<Address> Addresses { get; set; }
    }

    public class Address
    {
        public int Id { get; set; }
        public string City { get; set; }

        public List<Person> Persons { get; set; }
    }

    public class CodeFirstContext : DbContext
    {
        public DbSet<Person> Persons { get; set; }
        public DbSet<Address> Addresses { get; set; }
    }
}
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 -