简体   繁体   English

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

[英]Error : INSERT statement conflicted with the FOREIGN KEY constraint

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. 我正在使用asp.net mvc4,c#和Entity Framework。

My comment model has a PostId property. 我的评论模型有一个PostId属性。

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Comments_dbo.Posts_PostId". INSERT语句与FOREIGN KEY约束“FK_dbo.Comments_dbo.Posts_PostId”冲突。 The conflict occurred in database Myproject, table "dbo.Posts", column 'PostId'. 冲突发生在数据库Myproject,表“dbo.Posts”,列'PostId'中。
The statement has been terminated. 该语句已终止。

EDIT : 编辑:

I've noticed that, my comment.PostId is equal to 0 when SaveChanges() is called 我注意到,当我调用SaveChanges()时,我的comment.PostId等于0

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 我注意到,如果我的CreateComment视图中有@Html.HiddenFor(model => model.PostId) ,那么我已经没有错误,但是当我点击添加评论时没有任何反应

PostController : 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) : 创建视图(调用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 partial view (call the CreateComment view) : 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>
 }

EDIT 2 编辑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: 你应该在你的评论模型上设置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);
    }

Finally, I fix the issue by changing my CreateComment (httpPost) ActionResult with the following : 最后,我通过使用以下内容更改我的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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 INSERT语句与FOREIGN KEY约束错误冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint error 错误-INSERT语句与FOREIGN KEY约束冲突 - Error - The INSERT statement conflicted with the FOREIGN KEY constraint 使用SimpleMembership的AddUserToRole时出错:INSERT语句与FOREIGN KEY约束冲突 - Error using AddUserToRole of SimpleMembership: INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint BulkInsert:INSERT语句与FOREIGN KEY约束冲突 - BulkInsert: The INSERT statement conflicted with the FOREIGN KEY constraint “ INSERT语句与FOREIGN KEY约束冲突 - "The INSERT statement conflicted with the FOREIGN KEY constraint SqlException:INSERT语句与FOREIGN KEY约束冲突 - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint SqlException INSERT语句与FOREIGN KEY约束冲突 - SqlException The INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与MVC中的FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in MVC INSERT 语句与 FOREIGN KEY 约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM