Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 218
Yosi Avatar asked May 08 '11 21:05

Yosi


1 Answers

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();
}
like image 97
Charandeep Singh Avatar answered Oct 30 '22 06:10

Charandeep Singh