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).
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.
Is there a way for MVC4 to generate the controller and views for me, like it does for one to many relationships?
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?
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):
<HttpPost()> _
<ValidateAntiForgeryToken()> _
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
I am using VS 2012 and EF 5.0
Here is my implementation:
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
with the following DbContext
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