Search code examples
asp.net-mvc-3entity-framework-4ef-code-firstscaffolding

MvcScaffolding: How to support many-to-many relationships between entities


I started using MVC 3 and used MvcScaffolding to scaffold these models:

namespace Conference.Models
{
    /*
     * Speaker can have many session
     * And session can have many speakers
     */

    public class Speaker
    {
        public Guid Id { get; set; }
        [Required]
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Session> Sessions { get; set; }
    }

    public class Session
    {
        public Guid Id { get; set; }

        [Required]
        public string Title { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public DateTime Hour { get; set; }

        public virtual ICollection<Speaker> Speakers { get; set; }
    }
}

After scaffolding these models, I can create sessions and speakers, but in the speakers view, I cannot choose any sessions, and in the sessions view I cannot choose any speakers.

How can I add these and make them mutliselect options, such that I can choose 10 speakers for one specific session, e.g.?

Thanks in advance, Yosy


Solution

  • You need this in your context class: (this will create an association table)

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<Speaker>()
                     .HasMany(parent => parent.Session)
                     .WithMany();
    }