多对多MVC 5模型代码先加入table

Many to many MVC 5 Model Code first join table

我有一个完美的工作代码,在团队和玩家之间有一对多的关系。团队端的下拉菜单有效,所有内容都存储在数据库中。

现在我想介绍一个加入table,这样一队可以有很多球员,一个球员可以加入很多球队。我在黑暗中跌跌撞撞,需要前进的帮助。请参阅下面的代码。提前致谢! /塔猪

控制器

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());
    }

型号:

命名空间_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; } 
} }

您只需将 Player 上的 Team 属性 更改为:

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

Entity Framework 将自动识别 M2M 存在并创建连接 table.