![](/img/trans.png)
[英]How to update/create many-to-many relational data in MVC Code-first using EF?
[英]MVC 5 - How to update relational table using EF code first
我對 MVC 5 比較陌生,並且在弄清楚如何更新關系表時遇到問題。 我首先使用 EF 代碼。 我花了很多時間尋找解決方案,但我找不到與我的代碼相關的任何內容,這就是為什么我別無選擇,只能在這里提問,所以如果已經回答了這個問題,我先道歉。
我將關系表包含在我的 Razor 視圖中,效果非常好。 但是當我想更新表格時,即使我當前的代碼沒有錯誤,它也不會更新。 我還嘗試添加一個額外的 Bind[(Include = "Id,FirstName,LastName")],但這使用了 Booking FirstName 和 LastName。 我不確定我的方法是否是“正確的”方法。 我的邏輯告訴我,我需要從視圖中獲取數據並在控制器中檢索它們,但我不知道如果我不能使用 Bind 或 db.Entry(item).State = EntityState.Modified 怎么辦?
預訂.cs
namespace Ventures.Innovation.InteractiveModel.Context
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Bookings
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Bookings()
{
AttendingPeople = new HashSet<AttendingPeople>();
}
public int Id { get; set; }
[Required]
[StringLength(128)]
public string AspNetUserFk { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
public virtual AspNetUsers AspNetUsers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AttendingPeople> AttendingPeople { get; set; }
}
}
參加人.cs
namespace Ventures.Innovation.InteractiveModel.Context
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class AttendingPeople
{
public int Id { get; set; }
public int BookingId { get; set; }
[Required]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
public virtual Bookings Bookings { get; set; }
}
}
控制器
// GET: AdminHome/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bookings bookings = db.Bookings.Find(id);
if (bookings == null)
{
return HttpNotFound();
}
ViewBag.AspNetUserFk = new SelectList(db.AspNetUsers, "Id", "Email", bookings.AspNetUserFk);
var attendingPeople = db.AttendingPeople.Where(a => a.BookingId == id).ToList();
bookings.AttendingPeople = attendingPeople;
return View(bookings);
}
// POST: AdminHome/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,AspNetUserFk,Date,FirstName,LastName")] Bookings bookings)
{
if (ModelState.IsValid)
{
db.Entry(bookings).State = EntityState.Modified;
db.SaveChanges();
var editedAttendingPeople = db.AttendingPeople.Where(a => a.BookingId == bookings.Id).ToList();
foreach (var item in editedAttendingPeople)
{
db.Entry(item).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AspNetUserFk = new SelectList(db.AspNetUsers, "Id", "Email", bookings.AspNetUserFk);
return View(bookings);
}
看法
@model Ventures.Innovation.InteractiveModel.Context.Bookings
@{
ViewBag.Title = "Edit booking";
}
<h2>Edit booking</h2>
<hr />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
</div>
<div class="form-group">
@Html.LabelFor(model => model.AspNetUserFk, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AspNetUserFk", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AspNetUserFk, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>
@if (Model.AttendingPeople.Count > 0)
{
@Html.Label("Attending people")
foreach (var attendingPeople in Model.AttendingPeople)
{
<div class="form-group">
<div class="col-md-10">
@Html.LabelFor(modelItem => attendingPeople.FirstName, htmlAttributes: new { @class = "control-label col-md-5", @style = "padding-left: 0;" })
@Html.LabelFor(modelItem => attendingPeople.LastName, htmlAttributes: new { @class = "control-label col-md-5", @style = "padding-left: 0;" })
</div>
<div class="col-md-10">
@Html.EditorFor(modelItem => attendingPeople.FirstName, new { htmlAttributes = new { @class = "form-control col-md-5", @style = "display: initial;" } })
@Html.EditorFor(modelItem => attendingPeople.LastName, new { htmlAttributes = new { @class = "form-control col-md-5", @style = "display: initial;" } })
</div>
</div>
}
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save changes" class="btn btn-primary" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我想將更新后的數據保存到數據庫中的 AttendingPeople 表中,但沒有任何反應。
感謝 JARRRRG 在這里幫助我。 :)
為了解決這個問題,我需要確保我的命名完全相同。 顯然,這就是它從視圖到控制器的查找/綁定方式。 我還需要確保我使用了 for 循環,以便集合可以區分對象。
所以這是我更新的觀點:
@if (Model.AttendingPeople.Count > 0)
{
@Html.Label("Attending people")
var attendingPeople = Model.AttendingPeople.ToArray();
foreach (int i = 0; i < attendingPeople.Length; i++)
{
@Html.HiddenFor(modelItem => attendingPeople[i].Id)
<div class="form-group">
<div class="col-md-10">
@Html.LabelFor(modelItem => attendingPeople[i].FirstName, htmlAttributes: new { @class = "control-label col-md-5", @style = "padding-left: 0;" })
@Html.LabelFor(modelItem => attendingPeople[i].LastName, htmlAttributes: new { @class = "control-label col-md-5", @style = "padding-left: 0;" })
</div>
<div class="col-md-10">
@Html.EditorFor(modelItem => attendingPeople[i].FirstName, new { htmlAttributes = new { @class = "form-control col-md-5", @style = "display: initial;" } })
@Html.EditorFor(modelItem => attendingPeople[i].LastName, new { htmlAttributes = new { @class = "form-control col-md-5", @style = "display: initial;" } })
</div>
</div>
}
}
這是我的新編輯:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,AspNetUserFk,Date,FirstName,LastName")] Bookings bookings, ICollection<AttendingPeople> attendingPeople)
{
if (ModelState.IsValid)
{
db.Entry(bookings).State = EntityState.Modified;
db.SaveChanges();
foreach (var item in attendingPeople)
{
item.BookingId = bookings.Id;
db.Entry(item).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AspNetUserFk = new SelectList(db.AspNetUsers, "Id", "Email", bookings.AspNetUserFk);
bookings = db.Bookings.Include(at => at.AttendingPeople).SingleOrDefault(b => b.Id == bookings.Id)
return View(bookings);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.