我有一个完美的工作代码,团队和玩家之间有一对多的关系。 Team side的下拉菜单工作,evertything存储在db。
中现在我想介绍一个联接表,这样一个团队可以有很多玩家,一个玩家可以加入很多团队。我在黑暗中磕磕绊绊,需要前进的帮助。请参阅下面的代码。提前致谢! / Tha Pig
控制器
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()); }
模型:
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; } } }
答案 0 :(得分:1)
您只需将Team
上的Player
属性更改为:
public virtual ICollection<Team> Teams { get; set; }
实体框架将自动识别存在的M2M并创建连接表。