Code First EF 4.1 : Building Many to Many Relationship

Code First EF 4.1 : Building Many to Many Relationship

Rate This
  • Comments 8

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" };




        using (var ctx = new EmpContext())

Generated database would look like



Leave a Comment
  • Please add 6 and 2 and type the answer here:
  • Post
  • Nice! Thanks.

    Now I'm wondering: What if I already have an existing list of Emp's? I want to associate the Project with some of those existing Emps. How would I do that? Your code above creates brand new Emps and adds those to the Emp table.

  • Please tell me how to Add、Delete、Modify Data??

  • if ProjectEmps has some properties: Weight ...

    how to add delete update   thanks a lot

  • How can I add some data to the ProjectEmps table? i.e. LastActivity:date, Commission:money etc.

  • To add to the child table you need to first get the employee to an object from DB then use it instead of creating new. After it should look the same.

  • thank's

    but i have this database :

    commande(cmd_Id, Client, Data)    cmd_id is pimary key

    produit(pro_Id,libelle)   pro_id is primary key

    ligneCmd(Cmd_Id,pro_id)    pro_id and cmd id are primary keys and foreign keys

    help me pleaze thank's

  • How do you handle if you have another collumn in the association table(ProjectEmps), for exp : project assined date,

    You microsofts guys should come up with real and complex problem not chota problems like above.



  • Can you tell me if i want to add an extra field in ProjectEmps table how can i do that!

Page 1 of 1 (8 items)