tha pig
tha pig

Reputation: 35

Many to many MVC 5 Model Code first join table

I have a perfect working code with One to many relationship between Team and Player. The drop down menu on Team side works and evertything is stored in db.

Now i want to introduce a join table so that one Team can have many players, and one player can join many team. I´m stumbling in the dark and need help forward. See my code below. Thanks in advance! /Tha Pig

Controllers

PlayerController.cs

namespace _1_to_N.Controllers {

public class PlayerController : Controller
{
    private _1_to_NContext db = new _1_to_NContext();

    // GET: Player
    public ActionResult Index()
    {
        var players = db.Players.Include(p => p.Team);
        return View(players.ToList());
    }

TeamController.cs

namespace _1_to_N.Controllers {

public class TeamController : Controller
{
    private _1_to_NContext db = new _1_to_NContext();

    // GET: Team
    public ActionResult Index()
    {
        return View(db.Teams.ToList());
    }

MODELS:

namespace _1_to_N.Models.cs

{ public class _1_to_NContext : DbContext {

    public _1_to_NContext() : base("name=_1_to_NContext")
    {
    }

    public System.Data.Entity.DbSet<_1_to_N.Models.Team> Teams { get; set; }

    public System.Data.Entity.DbSet<_1_to_N.Models.Player> Players { get; set; }

} }

Player.cs

namespace _1_to_N.Models {

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
    public int TeamId { get; set; }

    public virtual Team Team { get; set; }
} }

Team.cs

namespace _1_to_N.Models{

public class Team
{
    public int TeamId { get; set; }
    [Required]
    public string Name { get; set; }
    public string City { get; set; }
    public DateTime Founded { get; set; }

    public virtual ICollection<Player> Players { get; set; } 
} }

Upvotes: 2

Views: 1091

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239200

You just need to alter the Team property on Player to:

public virtual ICollection<Team> Teams { get; set; }

Entity Framework will automatically discern an M2M exists and create a join table.

Upvotes: 2

Related Questions