正如標題所示。我試圖爲管理員啓用刪除和編輯系統。編輯和刪除數據庫中的特定用戶
管理員指定與數據庫中的數據相匹配的日期時間和用戶ID,並顯示給出的選擇。
現在我需要知道如何編輯或刪除特定的數據。
型號:
public partial class Stamping
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserId { get; set; }
[Key]
[Column(Order = 1)]
[DataType(DataType.DateTime)]
public DateTime Timestamp { get; set; }
[Required]
[StringLength(3)]
public string StampingType { get; set; }
public virtual User User { get; set; }
}
查看:
@model IEnumerable<Aviato.Models.Stamping>
@Html.DisplayNameFor(model => model.UserId)
@Html.DisplayNameFor(model => model.Timestamp)
@Html.DisplayNameFor(model => model.StampingType) @foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.UserId)
@Html.DisplayFor(modelItem => item.Timestamp)
@Html.DisplayFor(modelItem => item.StampingType)
@Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.UserId })}
控制器:
[AuthenticateRoles(Roles = "admin")]
public class StampingsController : Controller
{
private AviatoModel db = new AviatoModel(); //Database Connection.
public ActionResult Index(Stamping model)
{
var startTime = model.Timestamp;
var endTime = model.Timestamp.AddDays(1);
var stampings = db.Stampings.Where(s => s.Timestamp >= startTime && s.Timestamp <= endTime)
.Where(s => s.UserId == model.UserId).ToList();
return View(stampings);
}
public ActionResult Edit(int? id)
{
var stamping = db.Stampings.Find(id); /*An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code. Additional information: The number of primary key values passed must match number of primary key values defined on the entity.*/
ViewBag.UserId = new SelectList(db.Users, "UserId", "SocialSecurityNumber", stamping.UserId);
return View(stamping);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserId,Timestamp,StampingType")] Stamping stamping)
{
if (ModelState.IsValid)
{
db.Entry(stamping).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "UserId", "SocialSecurityNumber", stamping.UserId);
return View(stamping);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Stamping stamping = db.Stampings.Find(id); //Same error as in Edit ActionResult.
if (stamping == null)
{
return HttpNotFound();
}
return View(stamping);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Stamping stamping = db.Stampings.Find(id);
db.Stampings.Remove(stamping);
db.SaveChanges();
return RedirectToAction("Index");
}
如何將我解決這個問題? Iv'e試着圍繞錯誤搜索,但沒有成功。
所有幫助將不勝感激!
你有什麼錯誤? – DavidG 2014-09-26 09:23:29
在EntityFramework.dll中發生類型爲「System.ArgumentException」的異常,但未在用戶代碼中處理。附加信息:傳遞的主鍵值數量必須與實體上定義的主鍵值數量匹配。 – Qvadriologic 2014-09-26 09:24:02
是的,在兩個... – Qvadriologic 2014-09-26 09:27:10