I've got this error on the line
db.Comments.Add(comment);
db.SaveChanges();
and I can't fix it... What's the issue? I've read many question on that issue, but can't find from where the issue come in my code.
I'm using asp.net mvc4, c# and Entity Framework.
My comment model has a PostId
property.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Comments_dbo.Posts_PostId". The conflict occurred in database Myproject, table "dbo.Posts", column 'PostId'.
The statement has been terminated.
EDIT :
I've noticed that, my comment.PostId is equal to 0 when SaveChanges() is called
I've noticed that, if I had @Html.HiddenFor(model => model.PostId)
in my CreateComment view, then i've got no error anymore, but nothing happens when I click to add the comment
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);
}
Create view (call the ListPost partial View) :
@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 partial view (call the CreateComment view) :
@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>
}
EDIT 2
Posts Table :
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);
Comments Table
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);
Thank you
you should set the PostId property on your Comment Model:
[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;
//here
comment.PostId = values["postId"];
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Create", "Post");
}
ViewBag.PostId = new SelectList(db.Posts, "PostId", "Content", comment.PostId);
return View(comment);
}
Finally, I fix the issue by changing my CreateComment (httpPost) ActionResult with the following :
[HttpPost]
public ActionResult CreateComment(FormCollection values, int id)
{
var comment = new Comment();
TryUpdateModel(comment);
/** ADD THIS LINE **/
Post post = db.Posts.Find(id);
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;
/*** ADD THIS TWO LINES ***/
comment.Post = post;
comment.PostId = post.PostId;
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Create", "Post");
}
ViewBag.PostId = new SelectList(db.Posts, "PostId", "Content", comment.PostId);
return View(comment);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.