Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC4 controller with Many to Many relationship
    text
    copied!<p>I have the two entities, Arena and Regulator, which have a many to many relationship between them. I have implemented what seems to be the EF code first accepted solution (see below).</p> <p>I am now stuck with implementing the controller views, so that when a user creates a regulator, he can select one or more arenas (probably with check boxes or multi select list), and when they create an arena, one or more regulators can be selected.</p> <p>Is there a way for MVC4 to generate the controller and views for me, like it does for one to many relationships?</p> <p>EDIT: From the initial comments, I now understand that I can add the selected arena to the Arenas navigation property of the regulator object. I have not been able to find the way to both add the selection list to the Edit (and Create) views, and then make the changes in the controller. Can anyone supply an example?</p> <p>EDIT2: I have code for the Edit actions that should work if EF did indeed update relationships (regulator.ArenaIDs is a list of integers I added to the regulator class, to get the selected item IDS from the MultiSelectList):</p> <pre><code>&lt;HttpPost()&gt; _ &lt;ValidateAntiForgeryToken()&gt; _ Function Edit(ByVal regulator As Regulator) As ActionResult If ModelState.IsValid Then For Each i In regulator.ArenaIDs regulator.Arenas.Add(db.Arenas.Find(i)) Next db.Entry(regulator).State = EntityState.Modified db.SaveChanges() Return RedirectToAction("Index") End If Return View(regulator) End Function </code></pre> <p>I am using VS 2012 and EF 5.0</p> <p>Here is my implementation:</p> <pre><code>Public Class Arena Public Property Id As Integer Public Property Name As String Public Overridable Property Regulators() As ICollection(Of Regulator) End Class Public Class Regulator Public Property Id As Integer Public Property Name As String Public Overridable Property Arenas() As ICollection(Of Arena) End Class </code></pre> <p>with the following DbContext</p> <pre><code>Public Class TslilContext Inherits DbContext Public Property Arenas As DbSet(Of Arena) Public Property Regulators As DbSet(Of Regulator) Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder) modelBuilder.Entity(Of Arena)(). _ HasMany(Function(c) c.Regulators). _ WithMany(Function(p) p.Arenas). _ Map(Function(m) m.MapLeftKey("ArenaId") m.MapRightKey("RegulatorId") m.ToTable("Tiers") End Function) End Sub </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload