我碰到一個錯誤,指出:我打了一個錯誤,當我嘗試一個新的評論添加到我的數據庫
INSERT語句衝突與外鍵約束「FK_dbo.Comments_dbo.Posts_PostID」。數據庫「MVCProjectApp.Models.DBPostsContext」,表「dbo.Posts」,列「PostID」發生衝突。
該聲明已被終止。
我很失落,不知道該怎麼辦
下面是創建註釋
@model MVCProjectApp.Models.Comment
@{
ViewBag.Title = "Create Comment";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Comments</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Timestamp)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Timestamp)
@Html.ValidationMessageFor(model => model.Timestamp)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "~/FullPost/Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
這是我傳遞的帖子ID來註釋創建ActionLink的
//
// GET: /Comment/Create
public ActionResult Create()
{
ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title");
return View();
}
//
// POST: /Comment/Create
[HttpPost]
public ActionResult Create(Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title", comment.PostID);
return View(comment);
}
這裏是評論模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCProjectApp.Models
{
public class Post
{
public int PostID { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public DateTime Timestamp { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public int PostID { get; set; }
public string Username { get; set; }
public string Message { get; set; }
public DateTime Timestamp { get; set; }
public virtual Post Post { get; set; }
}
}
它說,您提供的外鍵在主表中不存在。 –