EF CodeFirst Many 2 Many Relationship Insert RRS feed

  • Question

  • I've created a few models, two in particular, Project and Category. It generated my database just fine, creating a ProjectCategory table with both foreign keys. My model Project has a collection of Categories and vice-versa. I'm trying to figure out how, in my Project/Create view, to have it allow me to add multiple categories for the new Project. I managed to select all the categories in the ProjectsController and in the view I created a foreach loop to add <input> tags of type checkbox for each category. This displays all the Categories and their respective Ids as values and Names as text just fine. Now since it auto-generated my tables and created my ProjectCategory table, how do I access it? Do I need to make another ProjectCategory model and add it to the context model? I'm confused.
    Saturday, January 28, 2012 10:43 PM


  • Hi Phenomin,

    There are navigations for the two entities:

        .HasMany(p => p.Categorys)
        .WithMany(t => t.Projects)
        .Map(m =>
                m.MapLeftKey(p => p.ProjectId, "CustomFkToProjectId");
                m.MapRightKey(t => t.CategoryId, "CustomFkToCategoryId");

    var p= new Project{Categorys=new List<Category>()};
    p.Categorys.Add(new Category{});

    Have a nice day.

    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, January 31, 2012 5:52 AM