我得到這個錯誤就行了錯誤:INSERT語句衝突與外鍵約束
db.Comments.Add(comment);
db.SaveChanges();
,我不能修復它...有什麼問題?我已經閱讀了關於該問題的許多問題,但無法從代碼中發現問題的來源。
我使用的是asp.net mvc4,c#和Entity Framework。
我的評論模型有一個PostId
屬性。
INSERT語句衝突與外鍵約束 「FK_dbo.Comments_dbo.Posts_PostId」。衝突發生在 數據庫Myproject中,表「dbo.Posts」,列'PostId'。
該聲明已被終止。
編輯:
我注意到,我的comment.PostId等於0時,調用SaveChanges()被調用
我發現,如果我在我的CreateComment視圖中有@Html.HiddenFor(model => model.PostId)
,那麼我再也沒有錯誤了,但是當我點擊添加評論時沒有任何反應
PostController
:
public ActionResult ListPost()
{
var post = db.Posts.ToList();
return PartialView("ListPost", post);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection values)
{
var post = new Post();
TryUpdateModel(post);
if (ModelState.IsValid)
{
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var userid = user.UserId;
post.UserId = userid;
post.Date = DateTime.Now;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Create", "Post");
}
return View(post);
}
public ActionResult CreateComment()
{
ViewBag.PostId = new SelectList(db.Posts, "PostId", "Content");
return View("CreateComment");
}
[HttpPost]
public ActionResult CreateComment(FormCollection values)
{
var comment = new Comment();
TryUpdateModel(comment);
if (ModelState.IsValid)
{
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var userid = user.UserId;
comment.UserId = userid;
comment.Date = DateTime.Now;
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Create", "Post");
}
ViewBag.PostId = new SelectList(db.Posts, "PostId", "Content", comment.PostId);
return View(comment);
}
創建視圖(調用ListPost局部視圖):
@model Myproject.Models.Post
@using (Html.BeginForm("Create", "Post", FormMethod.Post))
{
<legend>Add Post</legend>
<div class="editor-field">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
<input type="file" name="Photo" id="Photo"/>
</div>
<p>
<input type="submit" value="Post" />
</p>
}
@{Html.RenderAction("ListPost", "Post");}
ListPost局部視圖(調用CreateComment視圖):
@model IEnumerable<MyProject.Models.Post>
@foreach (var item in Model.OrderByDescending(x => x.Date))
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Content)
</td>
</tr>
<tr>
<td>
@Html.DisplayFor(modelItem => item.Date)
<span>@Html.DisplayFor(modelItem => item.Users.UserName)</span>
</td>
</tr>
<tr>
<td> @Html.ActionLink("Add Comment", "CreateComment", new {id=item.PostId})</td>
</tr>
}
編輯2
文章頁數:
CREATE TABLE [dbo].[Posts] (
[PostId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[Content] NVARCHAR (MAX) NULL,
[Date] DATETIME NOT NULL,
[Picture] VARBINARY (MAX) NULL,
CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED ([PostId] ASC),
CONSTRAINT [FK_dbo.Posts_dbo.UserProfile_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[Posts]([UserId] ASC);
評論表
CREATE TABLE [dbo].[Comments] (
[CommentId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[PostId] INT NOT NULL,
[Content] NVARCHAR (MAX) NULL,
[Date] DATETIME NOT NULL,
CONSTRAINT [PK_dbo.Comments] PRIMARY KEY CLUSTERED ([CommentId] ASC),
CONSTRAINT [FK_dbo.Comments_dbo.Posts_PostId] FOREIGN KEY ([PostId]) REFERENCES [dbo].[Posts] ([PostId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_PostId]
ON [dbo].[Comments]([PostId] ASC);
謝謝
add PostId在哪裏設置。調用savechanges時它是空還是默認?該字段是否標記爲DB上的標識? –
@soadyp我應該在哪裏添加PostId設置?我真的不知道如何查看它是否爲空或默認值。是的,我的PostId字段在我的發佈表中標記爲身份,在我的評論表中顯示爲FK。 – AlternateChris
@soadyp所以,當調用savechanges時,我的PostId等於0 – AlternateChris