我遇到了一个错误,上面写着:
INSERT 语句与 FOREIGN KEY 约束“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")
}
这是我将 postid 传递给评论创建的 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; }
}
}