Wriju's BLOG

.NET, Cloud and everything

Code First EF 4.1 : Building Many to Many Relationship

Since we do not have any designer question might arise how can we create Many to Many relationship in Code First 4.1. Here it is

public class Emp
{
    public Emp()
    {
        Projects = new HashSet<Project>();
    }

    public int EmpId { get; set; }
    public string EmpName { get; set; }
    public ICollection<Project> Projects { get; set; }
}

public class Project
{
    public Project()
    {
        Emps = new HashSet<Emp>();
    }

    public int ProjectId { get; set; }
    public string ProjectName { get; set; }
    public ICollection<Emp> Emps { get; set; }
}

public class EmpContext : DbContext
{
    public DbSet<Emp> Emps { get; set; }
    public DbSet<Project> Projects { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var p1 = new Project() { ProjectName = "Fun Boat" };
        var p2 = new Project() { ProjectName = "Jumbo Jet" };
        var p3 = new Project() { ProjectName = "Free Zoo" };

        var e1 = new Emp() { EmpName = "Wriju" };
        var e2 = new Emp() { EmpName = "Wrishika" };
        var e3 = new Emp() { EmpName = "Saswati" };

        p1.Emps.Add(e1);
        p1.Emps.Add(e2);

        p2.Emps.Add(e2);
        p2.Emps.Add(e3);

        p3.Emps.Add(e3);
        p3.Emps.Add(e1);

        using (var ctx = new EmpContext())
        {
            ctx.Projects.Add(p1);
            ctx.Projects.Add(p2);
            ctx.Projects.Add(p3);
                
            ctx.SaveChanges();
        }
    }
}

Generated database would look like

image

Namoskar!!!