Niclas Söderberg February 2016

Trying to create a Forum in MVC 5 / ASP.NET

I'm trying to create a basic forum in ASP.NET MVC 5 and I am really stuck at a "The INSERT statement conflicted with the FOREIGN KEY constraint" error. I will post my class and controller for this assignment and an image that illustrates how I want this to work.

Thread.cs

namespace BlogProject.Models
{
    public class Thread
    {
        [Key]
        public int ThreadId { get; set; }
        public DateTime? PostDate { get; set; }
        public string ThreadText { get; set; }
        public string ThreadTitle { get; set; }
        public virtual ApplicationUser UserProfile { get; set; }
        public string GetUserName { get; set; }

        public virtual ICollection<Post> Posts { get; set; }
    }
    public class Post
    {
        public int PostId { get; set; }
        public string PostTitle { get; set; }
        public string PostText { get; set; }
        public DateTime? PostDate { get; set; }
        public virtual ApplicationUser UserProfile { get; set; }

        public virtual Thread Thread { get; set; }
        //[ForeignKey("Thread")]
        public int ThreadId { get; set; }

    }
}

PostsController.cs

// POST: Posts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PostId,PostTitle,PostText,PostDate,ThreadId")] Post post,Thread thread)
{
    if (ModelState.IsValid)
    {
        db.Posts.Add(post);
        db.SaveChanges();
        return RedirectToAction("Threads");
    }

    ViewBag.ThreadId = new SelectList(db.Threads, "ThreadId", "ThreadText", post.ThreadId);
    return View("Details");
}

This is how I want it to work:

Forum goal If you think the information here is not sufficien

Answers


anand February 2016

First change the Postmodel because your not assigning Primary Key and foreign Key

public class Post
{
    [Key]
    public int PostId { get; set; }
    .
    public int ThreadId { get; set; }
    [ForeignKey("ThreadId")]
    public virtual Thread Thread { get; set; }
}

In the controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Thread thread)

Because in the view page you have used only

@model BlogProject.Models.Thread

The post object will be null and try 'thread'

db.Posts.Add(post);

hope this helps

Post Status

Asked in February 2016
Viewed 3,409 times
Voted 11
Answered 1 times

Search




Leave an answer