很多很多MVC 5模型首先写入连接表

时间:2015-01-14 12:57:54

标签: c# entity-framework asp.net-mvc-5 many-to-many

我有一个“部分”工作代码,团队和玩家(以及联结表TeamPlayers)之间存在多对多的关系。 Team和Player端的下拉菜单不起作用。虽然数据存储在db(Player和Team表)中,但不存在于联结表TeamPlayers中。

我希望在我看来有可能将当前玩家和当前团队连接起来,也就是说,将当前TeamId保存到我的联结表中的TeamId(以及PlayerId到PlayerId)。最后一个插入步骤是....我完全陷入困境.... 感谢各种帮助。请参阅下面的代码,并在必要时提出更多要求。提前致谢! / Tha Pig

模型m2mContext.cs

public class m2mContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, please use data migrations.
        // For more information refer to the documentation:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx

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

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

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

    }

Model Team.cs

namespace m2m.Models
{
    public class Team
    {
        public int TeamId { get; set; }
        [Required]
        public string TeamName { get; set; }

        public int PlayerId { get; set; }
        public virtual ICollection<Player> Players { get; set; } // This is new

    }
}

Model Player.cs

namespace m2m.Models
{
    public class Player
    {
        public int PlayerId { get; set; }
        public string PlayerName { get; set; }
        public int TeamId { get; set; }

        // public virtual Team Team { get; set; } // This is new

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

Controller TeamController.cs

namespace m2m.Controllers
{
    public class TeamController : Controller
    {
        private m2mContext db = new m2mContext();

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

        // GET: Team/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Team team = db.Teams.Find(id);
            if (team == null)
            {
                return HttpNotFound();
            }
            return View(team);
        }

        // GET: Team/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Team/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "TeamId,TeamName,PlayerId")] Team team)
        {
            if (ModelState.IsValid)
            {
                db.Teams.Add(team);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(team);
        }

Controller PlayerController.cs

namespace m2m.Controllers
{
    public class PlayerController : Controller
    {
        private m2mContext db = new m2mContext();

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

        // GET: Player/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Player player = db.Players.Find(id);
            if (player == null)
            {
                return HttpNotFound();
            }
            return View(player);
        }

        // GET: Player/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Player/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "PlayerId,PlayerName,TeamId")] Player player)
        {
            if (ModelState.IsValid)
            {
                db.Players.Add(player);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(player);
        }

查看团队

创建

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Team</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.TeamName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TeamName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TeamName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PlayerId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PlayerId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PlayerId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

查看播放器

创建

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Player</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.PlayerName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PlayerName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PlayerName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TeamId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TeamId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TeamId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

2 个答案:

答案 0 :(得分:0)

由于我的代表,我无法发表评论,所以我会发布一个可能的答案。

我会将TeamPlayers添加到模型中,向玩家和/或团队控制器添加一个方法,将它们添加到TeamPlayer。

public System.Data.Entity.DbSet<m2m.Models.TeamPlayer> TeamPlayer{ get; set; }

在控制器中

public ActionResult AddtoTeam(int? Teamid)
public ActionResult AddPlayer(int? Playerid)

不完全确定这是你想要的。

答案 1 :(得分:0)

问题是您发布到了属性PlayerId / TeamId。这是一个M2M,因此这些领域不做任何事情。您必须提供一个多选项,最终将发布一个ID列表。然后,您可以使用此发布的ID列表从数据库中查找玩家/团队,并将其添加到各自的馆藏中。