错误:INSERT语句与FOREIGN KEY约束冲突

时间:2012-12-21 16:46:10

标签: c# sql entity-framework asp.net-mvc-4

我在这行上有这个错误

db.Comments.Add(comment);
db.SaveChanges();

我无法解决它...问题是什么?我在这个问题上已经阅读了很多问题,但无法从我的代码中找到问题所在。

我正在使用asp.net mvc4,c#和Entity Framework。

我的评论模型有PostId属性。

  

INSERT语句与FOREIGN KEY约束冲突   “FK_dbo.Comments_dbo.Posts_PostId”。冲突发生在   数据库Myproject,表“dbo.Posts”,列'PostId'。
  该声明已被终止。

编辑:

我注意到了,我的comment.PostId在调用SaveChanges()时等于0

我注意到,如果我的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);

谢谢

2 个答案:

答案 0 :(得分:1)

您应该在评论模型上设置PostId属性:

    [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);
    }

答案 1 :(得分:1)

最后,我通过使用以下内容更改我的CreateComment(httpPost)ActionResult来解决此问题:

  [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);
    }